#!/usr/bin/perl

use Test::WWW::Mechanize::CGIApp;
use Data::Printer;
use Test::More;

use strict;
use warnings;

=begin # tests:
Load records into registration form using request_form table pre-populated
with NGIS request details. Does not actually regsiter a new request. Tests for
correct operation of required_external_reference function. Tests for presence
& absence of required_external_ref session key
=cut

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

my $mech = get_mech();

my $dbh;

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

warn $@ if $@;

my $dbix = get_dbix();
my $cfg  = get_config(); # p $cfg->{settings}; exit;

drop_and_recreate($_) for qw/request_form/;
do_login();

my $ngis_id_1 = 'D000001';
my $ngis_id_2 = 'D000002';

{ # new db entries:
    # GeNEQ location (check it exist or create new):
    unless ( $dbix->select( 'referral_sources', 1,
            { organisation_code => 'GENEQN' } )->list ) {
        $dbix->insert('parent_organisations', { parent_code => 'GENEQN',
            description => 'GENEQ NEWCASTLE', referral_type_id => 3 });
        my $parent_id = get_last_insert_id('parent_organisations');
        my %h = ( display_name => 'GeNEQ Newcastle', organisation_code => 'GENEQN',
            parent_organisation_id => $parent_id, referral_type_id => 3 );
        $dbix->insert('referral_sources', \%h);
    }
    unless ( $dbix->select( 'referral_sources', 1,
            { organisation_code => 'GENEQS' } )->list ) {
        $dbix->insert('parent_organisations', { parent_code => 'GENEQS',
            description => 'GENEQ SHEFFIELD', referral_type_id => 3 });
        my $parent_id = get_last_insert_id('parent_organisations');
        my %h = ( display_name => 'GeNEQ Sheffield', organisation_code => 'GENEQS',
            parent_organisation_id => $parent_id, referral_type_id => 3 );
        $dbix->insert('referral_sources', \%h);
    }
    # referrer & referrer_department for GeNEQ location (check exist or create new):
    unless ( $dbix->select( 'referrers', 1,
            { national_code => 'C2345678' })->list ) {
        $dbix->insert('referrers', { name => 'White A', national_code => 'C2345678',
            referral_type_id => 1 });
        my $ref_id = get_last_insert_id('referrers');
        $dbix->select('parent_organisations', 'id', { parent_code => 'GENEQN' })
            ->into(my $parent_id);
        $dbix->insert('referrer_department', { parent_organisation_id => $parent_id,
            referrer_id => $ref_id, hospital_department_code => 823 }); # haem OK for this
    }
    # referrer & referrer_department for GeNEQ location (check exist or create new):
    unless ( $dbix->select( 'referrers', 1,
            { national_code => 'C3456789' })->list ) {
        $dbix->insert('referrers', { name => 'Silver A', national_code => 'C3456789',
            referral_type_id => 1 });
        my $ref_id = get_last_insert_id('referrers');
        $dbix->select('parent_organisations', 'id', { parent_code => 'GENEQS' })
            ->into(my $parent_id);
        $dbix->insert('referrer_department', { parent_organisation_id => $parent_id,
            referrer_id => $ref_id, hospital_department_code => 823 }); # haem OK for this
    }
    { # register 2 new request_form rows:
        {
            my $ref_src_id = $dbix->select('referral_sources', 'id', 
                { organisation_code => 'GENEQN' })->list;
            my %h = ( # patient already registered in patients:
                id => $ngis_id_2, last_name => 'brown', first_name => 'stan',
                dob => '1960-04-10', gender => 'M', nhs_number => 2222222222,
                location_name => 'GeNEQ Newcastle', location_id => $ref_src_id,
                user_id => 1, referrer => 'White A [Molecular Genetics]',
                requested_by => 'Black T'
            );
            $dbix->insert('request_form', \%h);
        }
        {
            my $ref_src_id = $dbix->select('referral_sources', 'id', 
                { organisation_code => 'GENEQS' })->list;
            my %h = ( # patient doesn't already exist:
                id => $ngis_id_1, last_name => 'gray', first_name => 'olive',
                dob => '1966-07-11', gender => 'F', nhs_number => 3333333333,
                location_name => 'GeNEQ Sheffield', location_id => $ref_src_id,
                user_id => 1, referrer => 'Silver E [Molecular Genetics]',
                requested_by => 'Brown S'
            );
            $dbix->insert('request_form', \%h);
        }
    }
}
{ # new request for patient not already registered:
    $mech->get_ok('/register');                              # print_and_exit();
    $mech->form_name('request_form');

    $mech->submit_form( fields => { id => $ngis_id_1 } );    # print_and_exit();
    $mech->content_contains( 'Found 0 records', 'OK: record loaded');
    # session has required_external_ref key:
    $mech->get_ok('/test/dump_session');                     # print_and_exit();
    $mech->content_contains('required_external_ref',
        'OK: session contains expected key');
    # back to form:
    $mech->back();                                           # print_and_exit();
    $mech->submit();
    $mech->content_contains( 'New request', 'OK: patient record not loaded'); # print_and_exit();
    is( $mech->field('external_reference'),
       $ngis_id_1, 'OK: expected NGIS id loaded as external ref' );

    # session no longer contains required_external_ref:
    $mech->get_ok('/test/dump_session');                     # print_and_exit();
    $mech->content_lacks('required_external_ref',
        'OK: expected session key cleared');
}
{ # new request for patient who *is* already registered:
    $mech->get_ok('/register');                              # print_and_exit();
    $mech->form_name('request_form');

    $mech->submit_form( fields => { id => $ngis_id_2 } );    # print_and_exit();
    $mech->text_contains( 'Found 1 record', 'OK: patient record loaded');
    # session has required_external_ref key:
    $mech->get_ok('/test/dump_session');                     # print_and_exit();
    $mech->content_contains('required_external_ref',
        'OK: session contains expected key');                # print_and_exit();

    # back to form:
    $mech->back();                                           # print_and_exit();
    $mech->follow_link_ok( { url_regex => qr/select/i },
        'select patient using link' );                       # print_and_exit();
    $mech->text_contains('Add new location', 'OK: have new location textbox');

    $dbix->select('referral_sources', 'id', { organisation_code => 'GENEQN' })
        ->into( my $ref_src_id ); # warn $ref_src_id;
    $mech->field( referral_source_id => $ref_src_id ); # don't need unit num or location name
    $mech->submit();                                         # print_and_exit();

    $mech->content_contains( 'New request', 'OK: record loaded' ); # print_and_exit();
    is( $mech->field('external_reference'),
       $ngis_id_2, 'OK: expected NGIS id loaded as external ref' );
    # session no longer contains required_external_ref:
    $mech->get_ok('/test/dump_session');                     # print_and_exit();
    $mech->content_lacks('required_external_ref',
        'OK: expected session key cleared');
}
{ # register same patient as above but to other location, check NGIS id NOT loaded:
    $mech->get_ok('/register');                              # print_and_exit();
    $mech->form_name('register');

    $mech->submit_form( fields => { patient_no => 2222222222 } );  # print_and_exit();
    $mech->text_contains( 'Found 1 record', 'OK: patient record loaded');
    # session does not contain required_external_ref:
    $mech->get_ok('/test/dump_session');                     # print_and_exit();
    $mech->content_lacks('required_external_ref',
        'OK: session does not contain required_external_ref key');

    # back to form:
    $mech->back();                                           # print_and_exit();
    $mech->follow_link_ok( { url_regex => qr/select/i },
        'select patient using link' );                       # print_and_exit();
    $mech->text_contains('Add new location', 'OK: have new location textbox');

    # there are 2 'new' links, select 1st:
    $mech->follow_link_ok( { text => 'New', n => 1 }, 'following 1st link to New' ); # print_and_exit();
    $mech->text_contains( 'Newtown General Infirmary', 'OK: expected location found');
    is( $mech->field('external_reference'), '', 'OK: external ref field blank');
    # repeat and select 2nd link (GeNEQ Newcastle location):
    $mech->get_ok('/register');                              # print_and_exit();
    $mech->form_name('register');

    $mech->submit_form( fields => { patient_no => 2222222222 } ); # print_and_exit();
    $mech->text_contains( 'Found 1 record', 'OK: patient record loaded' );
    # session does not contain required_external_ref:
    $mech->get_ok('/test/dump_session');                     # print_and_exit();
    $mech->content_lacks('required_external_ref',
        'OK: session does not contain required_external_ref key');

    # back to form:
    $mech->back();                                           # print_and_exit();
    $mech->follow_link_ok( { url_regex => qr/select/i },
        'select patient using link' );                        # print_and_exit();
    # there are 2 'new' links, select 2nd:
    $mech->follow_link_ok( { text => 'New', n => 2 }, 'following 2nd link to New' ); # print_and_exit();
    $mech->text_contains( 'GeNEQ Newcastle', 'OK: expected location found');
    is( $mech->field('external_reference'), '', 'OK: external ref field blank');
}

done_testing(39);
