#!/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 => 17; # 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 $@;

# 'search' profile (dob):
$mech->get_ok('/search');            # print_and_exit();
{
    my %date_fields = (
        dob_day   => 31,
        dob_month => 1,
        dob_year  => 60, # too short
    );

    $mech->submit_form( fields => \%date_fields );           # print_and_exit();
    $mech->content_contains(
        dfv_format('year_digits'),
        'OK: year data length incorrect',
    );
    
    # year -> valid:
    $date_fields{dob_year} += 1900;
    # month -> invalid:
    $date_fields{dob_month}++;
    
    $mech->submit_form( fields => \%date_fields );            # print_and_exit();
    $mech->content_contains(
        dfv_format('invalid_date'),
        'OK: invalid date detected',
    );

    # month -> valid:
    $date_fields{dob_month}++;    
    # year -> future:
    $date_fields{dob_year} = DateTime->now->year() + 1;
    
    $mech->submit_form( fields => \%date_fields );            # print_and_exit();
    $mech->content_contains(
        dfv_format('future_date'),
        'OK: date in future detected OK',
    );

    # submit dob with missing year:
    $date_fields{dob_year} = undef; # warn Dumper \%date_fields;
    $mech->submit_form( fields => \%date_fields );            # print_and_exit();
    has_missing();
    
    # dob -> valid:
    $date_fields{dob_year} = DateTime->now->year() - 1;
    $mech->submit_form( fields => \%date_fields );           # print_and_exit();
    lacks_invalid();
}

# 'search' profile (specimen_code):
$mech->get_ok('/search');             # print_and_exit();
{
    $mech->field( specimen_code => 'BM');
    $mech->submit_form();                               # print_and_exit();
    
    has_invalid();
    
    $mech->field( specimen_code => 'BMA, PB'); # multiple specimens not supported
    $mech->submit_form();                              # print_and_exit();
    
    $mech->content_contains(
        dfv_format('alphanumeric'),
        'OK: invalid characters detected',
    );
}

# 'search' profile (nhs_number):
$mech->get_ok('/search');             # print_and_exit();
{
    $mech->field( nhs_number => 123456789 );
    $mech->submit_form();                               # print_and_exit();
    
    has_invalid();
    
    $mech->field( nhs_number => '0123456789' );           
    $mech->submit_form();                               # print_and_exit();
    
    lacks_invalid();
    
    # copes OK with spaces:
    $mech->field( nhs_number => '012 345 6789 ' );           
    $mech->submit_form();                               # print_and_exit();
    
    lacks_invalid();
}