#!/usr/bin/perl

use Test::WWW::Mechanize::CGIApp;

use strict;
use warnings;

use DateTime;
use POSIX;

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

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

    use DateTime;
    DateTime->DefaultLocale('en_GB');
}

my @data_fields = ( qw/GREEN Alan 01.Feb.1940 1011/, '111 111 1111', 'BMAT, PB' );

my $mech = get_mech();

my $dbh;

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

warn $@ if $@;

#drop_and_recreate('requests');

do_login();

# load main summary page for record #1:
$mech->get_ok('/search');                                   # print_and_exit();
{
    $mech->content_contains(
        '&raquo; Record Search',
        'OK: initial summary page loaded',
    );
    
    # submit empty form:
    $mech->submit_form();                                   # print_and_exit();
    
    $mech->has_tag_like(
        p => get_messages('search')->{empty_submission},
        'OK: expected empty form submission message'
    );                                                     # print_and_exit();
}

# search on lab_number:
{
    $mech->submit_form(
        fields => {
            lab_number => 1,
        }
    );                                               # print_and_exit();

    do_patient_fields('lab_number');
}

# search on last_name:
$mech->follow_link( text => 'Search', n => 1 );      # print_and_exit();
{
    $mech->submit_form(
        fields => {
            last_name => lc $data_fields[0],
        }
    );                                              # print_and_exit();
    
    do_patient_fields('last name');
}

# search on first_name:
$mech->follow_link( text => 'Search', n => 1 );      # print_and_exit();
{
    $mech->submit_form(
        fields => {
            first_name => $data_fields[1],
        }
    );                                              # print_and_exit();
    
    do_patient_fields('first name');
}

# search on nhs_number:
$mech->follow_link( text => 'Search', n => 1 );     # print_and_exit();
{
    $mech->submit_form(
        fields => {
            nhs_number => $data_fields[4],
        }
    );                                             # print_and_exit();
    
    do_patient_fields('nhs number');
}

# search on dob:
$mech->follow_link( text => 'Search', n => 1 );      # print_and_exit();
{
    $mech->submit_form(
        fields => {
            dob_day   => 1,
            dob_month => 2,
            dob_year  => 1940,
        }
    );                                                 # print_and_exit();

    do_patient_fields('dob');
}

# search on unit_number:
$mech->follow_link( text => 'Search', n => 1 );    # print_and_exit();
{
    $mech->submit_form(
        fields => {
            unit_number => $data_fields[3],
        }
    );                                                  # print_and_exit();
    
    do_patient_fields('unit number');
}

# search on location (id):
$mech->follow_link( text => 'Search', n => 1 );     # print_and_exit();
{
    $mech->submit_form(
        fields => {
            referral_source_id => 2,
        }
    );                                                 # print_and_exit();
    
    do_patient_fields('referral source');
}

# search on referrer:
$mech->follow_link( text => 'Search', n => 1 );          # print_and_exit();
{
    $mech->submit_form(
        fields => {
            referrer_name => 'Black',
        }
    );                                                      # print_and_exit();
    
    do_patient_fields('referrer name');
}

# search on specimen:
$mech->follow_link( text => 'Search', n => 1 );    # print_and_exit();
{
    $mech->submit_form(
        fields => {
            specimen_code => 'BMAT', # can't do multi-specimen search
        }
    );                                                     #  print_and_exit();
    
    do_patient_fields('specimen code');
}

# search on trial:
$mech->follow_link( text => 'Search', n => 1 );    # print_and_exit();
{
    $mech->submit_form(
        fields => {
            trial_id => 1, 
        }
    );                                                     #  print_and_exit();
    
    do_patient_fields('clinical trial');
}

# test sort_by/sort_order:
SKIP: {
    skip('TODO: how to test display order',1);
    $mech->follow_link( text => 'Search', n => 1 );    # print_and_exit();
    
    # search on last_name:
    $mech->submit_form(
        fields => {
            last_name => 'green',
        }
    );                                               # print_and_exit();
}

do_logout();

my $cfg = get_config(); # warn Dumper $cfg->{settings};

SKIP: {
    skip('only applicable if local network restriction in place',14)
        unless $cfg->{settings}->{local_network_restriction};
    
    # login as 'guest':
    # create new user:
    my %user = (
        username => 'guest',
        last_name => 'guest',
        first_name => 'a',
        password => 'qLDknwhYTQg38TFB2kQEtgu1fpY',
        user_location_id => 2,
        designation => 'guest',
        group_id => 2,
        active => 'yes',
    );
    my %user_location = (
        location_name => 'Old Surgery',
        region_code => 'B12345',
        active => 'yes',
    );
    
    my $dbix = get_dbix();
    # need to change region_code chars to 6 to allow GP surgery for test:
    $dbh->do( q!ALTER TABLE `user_locations` CHANGE COLUMN `region_code`
        `region_code` CHAR(6) NULL DEFAULT NULL AFTER `location_name`!);
    $dbix->insert( 'user_locations', \%user_location );
    $dbix->insert( 'users', \%user );

    do_login('a.guest', 'guessed');                          #  print_and_exit();
    
    # try to load case from inside current users network:
    $mech->get_ok('/search');                                 # print_and_exit();
    $mech->submit_form(
        fields => {
            lab_number => 1,
        }
    );                                                        # print_and_exit();

    do_patient_fields('lab_number');
    
    # try to load case from outside current users network:
    $mech->get_ok('/search');                                 # print_and_exit();
    $mech->submit_form(
        fields => {
            lab_number => 2,
        }
    );                                                        # print_and_exit();
    
    $mech->has_tag(
        p => get_messages('search')->{no_records_found},
        'OK: failed to find record',
    );                                                        # print_and_exit();
}

sub do_patient_fields {
    my $search_field = shift;
    
    my $i = 0;
    my $yr = DateTime->now->strftime('%y');
    my $output = "OK: data field [%s] for search on $search_field";
    
    foreach (@data_fields) {
        $mech->has_tag_like(
            td => qr($_),
            sprintf $output, ++$i,
        );
    }
    $mech->has_tag_like(
        a => qr(\w1/$yr),
        sprintf $output, ++$i,
    );    
}
