#!/usr/bin/perl

use Test::WWW::Mechanize::CGIApp;
use Test::Builder::Tester;

use Data::Dumper;

use strict;
use warnings;

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

=begin: tests:

=cut

BEGIN {
    $ENV{RDBO_DEBUG_ON} = 0;
    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 $@;

# re-create triggers - lost on table drop & create:
$dbh->do( qq!DROP TRIGGER IF EXISTS `$_`! )
    for qw(
        new_location
        new_referrer_on_request_insert
        new_referrer_on_request_update
    );

$dbh->do( q!CREATE TRIGGER `new_location` BEFORE INSERT ON `patient_case`
    FOR EACH ROW CALL do_new_location(NEW.referral_source_id)! );   
$dbh->do( q!CREATE TRIGGER `new_referrer_on_request_insert` BEFORE INSERT ON
    `requests` FOR EACH ROW CALL do_new_referrer(NEW.referrer_department_id)! );
$dbh->do( q!CREATE TRIGGER `new_referrer_on_request_update` BEFORE UPDATE ON
    `requests` FOR EACH ROW CALL do_new_referrer(NEW.referrer_department_id)! );

my $dbix = get_dbix();

# no entries in new_national_code:
{
    my $i = _count_new_national_code();
    is($i, 0, 'OK: no entries in new_national_code');
}
{ # new request with new referrer:
    $mech->get_ok('/request/add_new/2');                      # print_and_exit();

    my $referrer_code = 'C7654321';
    
    $mech->submit_form(
        fields => {
            request_number => 3,
            specimen => 'PB',
            referrer_code => $referrer_code,
        },
    );                                                        # print_and_exit();
    my $i = _count_new_national_code();
    is($i, 1, 'OK: new entry in new_national_code');
    
    my $result = _get_new_national_code($referrer_code);
    is($result, 1, 'OK: expected national code detected');
}

# add new referrer manually for request edit:
$dbix->insert('referrers', {
    name => 'Green AB', national_code => 'C2345678', referral_type_id => 1 });
$dbix->insert('referrer_department', {
    referrer_id => 6, parent_organisation_id => 1, hospital_department_code => 823 });

{ # edit referrer to one not used before:
    $mech->get_ok('/request/edit_request/3');                 # print_and_exit();
    
    my $referrer_code = 'C2345678';
    $mech->field(referrer_code => $referrer_code);
    $mech->field(error_code_id => 1);
    $mech->submit();                                          # print_and_exit();

    my $i = _count_new_national_code();
    is($i, 2, 'OK: new entry in new_national_code');
    
    my $result = _get_new_national_code($referrer_code);
    is($result, 1, 'OK: expected national code detected');
}

{ # edit referrer to one already used before:
    $mech->get_ok('/request/edit_request/3');                 # print_and_exit();
    
    my $referrer_code = 'C1234567';
    $mech->field(referrer_code => $referrer_code);
    $mech->field(error_code_id => 1);
    $mech->submit();                                          # print_and_exit();

    my $i = _count_new_national_code();
    is($i, 2, 'OK: no new entry in new_national_code'); # _hasn't_ increased count
}

{ # add 2 new referral sources:
    { # staging locations (just need a selection):
        my @sites = (
            [ 'Newtown District Hospital', 'ABC02', 1, 3 ],
            [ 'Oldtown District General',  'ABC03', 1, 3 ],
        );
        $dbh->do( q!INSERT INTO referral_sources (display_name, organisation_code,
                parent_organisation_id, referral_type_id) VALUES (?,?,?,?)!,
            undef, @$_ ) for @sites;
    }
}

{ # new request with new location:
    $mech->get_ok('/patient/select_patient/2');               # print_and_exit();

    $mech->field(unit_number => 'XYZ235');
    $mech->field(referral_source_id => 5);
    $mech->submit();                                          # print_and_exit();

    my $i = _count_new_national_code();
    is($i, 3, 'OK: new entry in new_national_code');

    my $result = _get_new_national_code('ABC02');
    is($result, 1, 'OK: expected national code detected');

    my $referrer_code = 'C2345678';
    $mech->submit_form(
        fields => {
            request_number => 4,
            specimen => 'PB',
            referrer_code => $referrer_code,
        },
    );                                                        # print_and_exit();

}

{ # edit request with new location:
    $mech->get_ok('/request/edit/4');                        # print_and_exit();
    
    $mech->field(referral_source_id => 6);
    $mech->field(error_code_id => 1);
    $mech->submit();                                          # print_and_exit();

    my $i = _count_new_national_code();
    is($i, 4, 'OK: new entry in new_national_code');

    my $result = _get_new_national_code('ABC03');
    is($result, 1, 'OK: expected national code detected');
}

sub _count_new_national_code {
    $dbix->query('select count(*) from new_national_code')->into( my $i );
    return $i;
}

sub _get_new_national_code {
    my $code = shift;
    my $sql = 'select 1 from new_national_code where national_code = ?';
    $dbix->query($sql, $code)->into( my $result );
    return $result;
}

do_logout();

