#!/usr/bin/perl

use Test::WWW::Mechanize::CGIApp;
# use HTML::TreeBuilder;
use Data::Dumper;

use strict;
use warnings;

use Test::More tests => 60; # use Test::More 'no_plan';

=begin # tests:
1) submit new user_location
2) change user_location to unique
3) get existing user from users table
4) register new user
5) test omission of each required field - skipped pending fix
6) retrieve new user, check field names & default permissions
7) change new user permissions - skipped pending fix
8) edit new username to another unique value & check new values
9) edit edited new username to a non-unqiue value & check failure
10) edit last_name to match new username & check success
11) register new user with same name as already exists
=cut

BEGIN {
    require 't/test-lib.pl';
}

my $mech = get_mech();

do_login();

my $dbh;

eval {
    $dbh = get_dbh() or die 'no database handle recieved from get_dbh';
};

warn $@ if $@;

# need to drop & re-create following tables:
drop_and_recreate('user_locations');

$mech->get_ok('/admin/user_location');      # print_and_exit();

$mech->content_contains(
    'Admin &raquo; User Locations',
    'requested page loaded ok',
);

$mech->submit_form(
    fields => {
        location_name => 'Bradford',
        active        => 'no',
    }
);                                          # print_and_exit();

foreach ( qw/Bradford/ ) { # RAE admin@bradford.net
  $mech->content_contains(
      qq!value="$_"!,
      'input field value detected ok',
  );
}

# change all fields:
$mech->get_ok('/admin/user_location/edit/1');      # print_and_exit();

$mech->content_contains(
    'Admin &raquo; Edit User Location',
    'requested page loaded ok',
);

$mech->submit_form(
    fields => {
        location_name => 'Leeds',
        active        => 'yes',
    }
);

foreach ( qw/Bradford/ ) { #  RAE admin@bradford.net
  $mech->content_lacks(
      qq!value="$_"!,
      'ok: old field value not detected',
    );
}
foreach ( qw/Leeds/ ) { # RR8 admin@leeds.net
  $mech->content_contains(
      qq!value="$_"!,
      'new field value detected ok',
  );
}

$mech->get_ok('/admin/user');         # print_and_exit();

### check title:
$mech->content_contains(
    'User Manager',
    'title matches',
);                                      # print_and_exit();

# get user admin:
$mech->submit_form(fields => { id => 1 });

### check default settings:
$mech->content_contains(
    '<span class="maroon">DEFAULT</span>',
    'OK: default settings used',
);                                    #  print_and_exit();

### check username selected:
is( $mech->value('userID', 1), 'ADMIN', 'OK: expected username found'); # print_and_exit();

my %new_user = (
    username => 'smith',
    last_name => 'smith',
    first_name => 'alan',
    password => 'passwd',
    user_location_id => 1,
    designation => 'bms',
    email => 'bms@somewhere.com',
    group_id => 2,
    active => 'yes',
);

{
    # register new user:
    $mech->follow_link_ok({ text => 'reset/new user', n => 1 });  # print_and_exit();

    ### check page loaded OK:
    $mech->content_contains(
        '<h2>Select a registered user or create new user:</h2>',
        'OK: page loaded',
    );                                        # print_and_exit();;

    # test each required field:
    foreach my $field ( keys %new_user ) { # warn $field;
        # create temp hash with one field missing:
        my %tmp_user = %new_user; # clone %new_user
        $tmp_user{$field} = undef; # warn Dumper \%tmp_user;

        # jump to correct form:
        $mech->form_number(2);
        $mech->submit_form( fields => \%tmp_user );

        has_dfv_errors();
    }

    # jump to correct form & submit intact %new_user:
    $mech->form_number(2);
    $mech->submit_form( fields => \%new_user );  # print_and_exit();

    # check we have success message:
    $mech->content_contains(
        get_messages('admin')->{user}->{create_success},
        'OK: new user created successfully',
    );                                         # print_and_exit();

    # check we can retreive new record
    # no need - changed update_user_details() to automatically retrieve:
    # $mech->submit_form(fields => { id => 2 });         # print_and_exit();

    my $i=0;
    foreach( qw/username last_name first_name designation email/ ) { # others diff. format
        $i++;
        # check we have new user fields:
        $mech->content_contains(
            qq!value="$new_user{$_}"!,
            "OK: new user field [$i] detected",
        );                                         # print_and_exit();
    }
    ### check default settings:
    $mech->content_contains(
        '<span class="maroon">DEFAULT</span>',
        'OK: default settings used',
    );                                       # print_and_exit();
}

# change user_permissions:
SKIP: {
    skip('cannot easily test which checkboxes are checked', 0);
    $mech->follow_link_ok({ text => 'change user permissions', n => 1 });  # print_and_exit();
}

my $new_username = 'wood';

# edit username - change to one that doesn't exist:
{
    $mech->get_ok('/admin/user');                       # print_and_exit();

    # get new user:
    $mech->submit_form(fields => { id => 2 });          # print_and_exit();

    # check we have correct username:
    $mech->content_contains(
        qq!name="username" value="$new_user{username}"!,
        'OK: new user loaded successfully',
    );                                               # print_and_exit();

    $mech->form_number(2);
    # change username to one that doesn't exist:
    $mech->field('username', $new_username);
    $mech->submit_form();                            # print_and_exit();

    # check it succeeded:
    $mech->content_contains(
        get_messages('admin')->{user}->{edit_success},
        'OK: username change successful',
    );                                               # print_and_exit();

    $mech->content_contains(
        qq!name="username" value="$new_username"!,
        'OK: username change successful',
    );
    my $i=0;
    # check all rest of fields still present:
    foreach( qw/last_name first_name designation email/ ) { # others diff. format
        $i++;
        # check we have new user fields:
        $mech->content_contains(
            qq!value="$new_user{$_}"!,
            "OK: new user field [$i] detected",
        );                                         # print_and_exit();
    }
}                                               # print_and_exit();

# now try to one that already exists:
{
    $mech->form_number(2);
    # change username to one that exists:
    $mech->field('username', 'admin');
    $mech->submit_form();                         # print_and_exit();

    # check it failed validation:
    has_dfv_errors();
}

# check we can edit non-username field:
{
    $mech->back;                                  # print_and_exit();

    $mech->form_name('user_update');
    # change last_name to match username:
    $mech->field('username',  $new_username); # needs resetting to original value
    $mech->field('last_name', $new_username);
    $mech->submit_form();                         # print_and_exit();

    # check it succeeded:
    lacks_dfv_errors();

    $mech->content_contains(
        qq!name="last_name" value="$new_username"!,
        'OK: new last_name detected',
    );                                              # print_and_exit();

    my $i=0;
    # check all rest of fields still present:
    $mech->content_contains(
        qq!name="username" value="$new_username"!,
        'OK: expected username detected',
    );                                              # print_and_exit();
    foreach( qw/first_name designation email/ ) { # others diff. format
        $i++;
        # check we have new user fields:
        $mech->content_contains(
            qq!value="$new_user{$_}"!,
            "OK: new user field [$i] detected",
        );                                          #  print_and_exit();
    }
}

# check we can edit all user fields:
{
    my %edit_user = (
      last_name   => 'editlastname',
      first_name  => 'editfirstname',
      email       => 'editnewuser@email.net',
      designation => 'enquirer',
    );

    lacks_dfv_errors();

    # select 'new user' form:
    $mech->form_number(2);
    $mech->submit_form(fields => \%edit_user);       # print_and_exit();

    # check it succeeded:
    $mech->content_contains(
        get_messages('admin')->{user}->{edit_success},
        'OK: username change successful',
    );                                               # print_and_exit();

    # check content
    $mech->content_contains(
        'editlastname',
        'OK: last name edited correctly'
    );
    $mech->content_contains(
        'editfirstname',
        'OK: firstname edited correctly'
    );
    $mech->content_contains(
        'editnewuser',
        'OK: email edited correctly'
    );
    $mech->content_contains(
        'enquirer',
        'OK: designation edited correctly'
    );
}

{ # duplicate first & last name:
    my %duplicate_user = (
        username => 'woody', # different to existing
        last_name => 'editlastname', # already exists
        first_name => 'editfirstname', # already exists
        password => 'passwd',
        user_location_id => 1,
        designation => 'bms',
        email => 'user@somewhere.com',
        group_id => 2,
        active => 'yes',
    );
    $mech->get_ok('/admin/user');                            # print_and_exit();
    $mech->form_number(2);
    $mech->submit_form( fields => \%duplicate_user );         # print_and_exit();

   # check it failed validation:
    has_dfv_errors();
    $mech->content_contains(
        'combination of first &amp; last names already used',
        'OK: duplicate first & last names detected'
    );

    # try to re-submit with duplicated username (as might happen with duplicate lname):
    $duplicate_user{last_name} = $duplicate_user{username}  = 'wood'; # already exists
    $mech->form_number(2);
    $mech->submit_form( fields => \%duplicate_user );         # print_and_exit();

    has_dfv_errors();

    # change username to unique, have unique fname + lname, should be OK:
    $duplicate_user{username} = 'woody'; # doesn't already exist
    $mech->form_number(2);
    $mech->submit_form( fields => \%duplicate_user );        #  print_and_exit();

    # check it succeeded:
    lacks_dfv_errors();
    $mech->content_contains(
        get_messages('admin')->{user}->{create_success},
        'OK: new user created successfully',
    );                                                       # print_and_exit();
}
# do_logout(); logout link not available for admin function
