#!/usr/bin/perl

# just testing for dfv errors using LIMS::Validation profiles:

use Test::WWW::Mechanize::CGIApp;
use Data::Dumper;

use strict;
use warnings;

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

=begin: tests:
1) 
=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 $@;

# change_password profile:
$mech->get_ok('/user/change_password');            # print_and_exit();
{
    my %pwd = (
        old_password => 'admin', # wrong
        new_password => 'foo', # too short
        new_password_confirm => 'bar', # doesn't match
    );
    
    my $msgs = get_messages('form_validator')->{user};
    
    $mech->submit_form( fields => \%pwd );           # print_and_exit();
    
    has_invalid();
    has_formvalidator_error($msgs->{new_password}->{LENGTH});
    has_formvalidator_error($msgs->{new_password_confirm}->{LENGTH});
    has_formvalidator_error($msgs->{pwds}->{DUPLICATION});
    
    # make new_password_confirm match new_password
    $pwd{new_password_confirm} = $pwd{new_password};
    
    $mech->submit_form( fields => \%pwd );           # print_and_exit();

    has_invalid();
    has_formvalidator_error($msgs->{new_password}->{LENGTH});
    has_formvalidator_error($msgs->{new_password_confirm}->{LENGTH});
    lacks_formvalidator_error($msgs->{pwds}->{DUPLICATION});
    
    # make new_password length ok, but new_password_confirm mistake:
    $pwd{new_password} = 'warthog';
    $pwd{new_password_confirm} = 'wartog';
    
    $mech->submit_form( fields => \%pwd );           # print_and_exit();
    
    lacks_invalid();
    lacks_formvalidator_error($msgs->{new_password}->{LENGTH});
    lacks_formvalidator_error($msgs->{new_password_confirm}->{LENGTH});
    has_formvalidator_error($msgs->{pwds}->{DUPLICATION});

    # make new_password_confirm match new_password
    $pwd{new_password_confirm} = $pwd{new_password};
    
    $mech->submit_form( fields => \%pwd );            # print_and_exit();

    my $user_messages = get_messages('user');
    $mech->content_contains(
        $user_messages->{old_pwd_mismatch},
        'OK: incorrect password detected',
    );
    
    # correct password & re-submit:
    $pwd{old_password} = 'adm1n';
    
    $mech->submit_form( fields => \%pwd );            # print_and_exit();
    
    lacks_invalid();
    # this tests MessageStack is working properly - old stash msg cleared:
    $mech->content_lacks(
        $user_messages->{old_pwd_mismatch},
        'OK: lacks pwd mismatch error',
    );    
    $mech->content_contains(
        $user_messages->{pwd_change_success},
        'OK: password change successful',
    );    
}

