#!/usr/bin/perl

# requires presence of config/.local/auto_reportable.yml file, or skips tests
# NOTE on failing tests...
# the yml file needs to have the joint result_summary_option and
# result_summary_expansion fields as the key. e.g.
#  report:
#    no evidence of Val617Phe JAK2 or CALR exon 9 mutation. Fluorescent fragment analysis is used to detect both abnormalities. The JAK2 ASO procedure has a limit of detection of 1% and the CALR procedure has an LOD of 5%:

#========== NEED TO CHANGE SCREENING TERMS TO MATCH YAML FILE ENTRIES ==========
our @screening_terms = (
    'Suspected myeloproliferative',
    'Follow-up CML (PB)',
);
#===============================================================================

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

use Data::Dumper;

use strict;
use warnings;

use constant TESTS => 35;

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

=begin: tests:
=cut

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

my $yaml = get_yaml('auto_reportable'); # warn Dumper $yaml;

SKIP: {
    skip('these tests require config/settings/.leeds/auto_reportable.yml file',TESTS) unless $yaml;
    do_all_tests();
}

sub do_all_tests {

my $mech = get_mech();

do_login();

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

# register data for auto_authorisation:
my $dbix = get_dbix();

my $result_summary_option = 'sample shows evidence of Val617Phe JAK2 mutation';

# 2 new screening terms (fresh tissue):
for (@screening_terms) {
	$dbix->insert('screens', {
		description => $_, category_id => 1, active => 'yes',
	});
}

$dbix->insert('diagnoses', {
    name => 'Consistent with chronic myeloproliferative disorder',
    diagnostic_category_id => 1, active => 'yes',
});
$dbix->insert('diagnoses', {
    name => 'Awaiting final diagnosis',
    diagnostic_category_id => 3, active => 'yes',
});

{ # lab_tests & lab_test_sample_type:
	my @test_ids;
	$dbix->insert('lab_tests', {
		field_label => 'JAK2 V617F', lab_section_id => 3, test_type => 'test',
		has_results => 'no', is_active => 'yes', test_name => 'jak2',
	});	push @test_ids, get_last_insert_id('lab_tests');
	$dbix->insert('lab_tests', {
		field_label => 'CML RQ', lab_section_id => 3, test_type => 'test',
		has_results => 'no', is_active => 'yes', test_name => 'cml',
	});	push @test_ids, get_last_insert_id('lab_tests');
	$dbix->insert('lab_tests', {
		field_label => 'RNA extraction', lab_section_id => 3, test_type => 'test',
		has_results => 'no', is_active => 'yes', test_name => 'rna_extraction',
	});	push @test_ids, get_last_insert_id('lab_tests'); # warn Dumper \@test_ids;

	my $sample_type_ids = $dbix->select('lab_section_sample_type',
		['sample_type_id'], { lab_section_id => 3 } )->flat; # warn Dumper $sample_type_ids;

	for my $id (@test_ids) {
		$dbix->insert('lab_test_sample_type',
			{ lab_test_id => $id, sample_type_id => $_ }) for @$sample_type_ids;
	}
}
$dbix->insert('result_summary_options', {
    description => $result_summary_option, lab_section_id => 3, is_active => 'yes',
});
my $result_summary_expansion =
    q!Fluorescent fragment analysis is used to detect both abnormalities. !
    . q!The JAK2 ASO procedure has a limit of detection of 1% and the CALR !
    . q!procedure has an LOD of 5%!;
$dbix->insert('result_summary_expansion',
    { result_summary_option_id => 2, description => $result_summary_expansion });
$dbix->insert('screen_lab_test', {screen_id => 3, lab_test_id => 10}); # JAK2
$dbix->insert('screen_lab_test', {screen_id => 3, lab_test_id => 12}); # JAK2
$dbix->insert('screen_lab_test', {screen_id => 4, lab_test_id => 11}); # CML
$dbix->insert('screen_lab_test', {screen_id => 4, lab_test_id => 12}); # CML

# register new:
$mech->get_ok('/request/add_new/2');
{
    $mech->submit_form(
        fields => {
            request_number => 3,
            specimen => 'PB',
            referrer_code => 'C1234567',
        },
    );                                                        # print_and_exit();

    $mech->has_tag(
        h3 => 'New request successful',
    );
}

# screen request with auto-reportable term:
$mech->get_ok('/screen/=/3');                                 # print_and_exit();
{
    $mech->form_name('initialScreen'); # 1st one is patient notes

    $mech->field(screen_id => 3);
    $mech->field(option_id => 1);
    $mech->submit();                                          # print_and_exit();

    $mech->text_contains(
        "Screened as $screening_terms[0]", # 1st one
        'OK: expected screen term found',
    );
}															  # print_and_exit();

# sign out tests:
$mech->get_ok('/worklist/display/3?display_format=Data+Entry');
{
    $mech->tick('request_lab_test_id', $_, 1) for (1,2); # sign off both tests
    $mech->field(status_option_id => 2);
    $mech->submit();                                          # print_and_exit();

    $mech->has_tag_like(
        p => qr(records updated successfully),
        'OK: update success',
    );                                                        # print_and_exit();

    for ('JAK2 V617F', 'RNA extraction', 'complete' ) {
        $mech->has_tag(td => $_);
    }
}

# section result summary should trigger auto-report/authorisation:
$mech->get_ok('/result/=/3');                                 # print_and_exit();
{
    $mech->form_name('molecular_results');
    $mech->field( _results_summary => $result_summary_option);
    $mech->submit();                                          # print_and_exit();
# if this fails, check contents of auto_reportable.yml are *exactly* as expected
# (saves many hrs of frustration!!!!!)
    $mech->has_tag_like(
        p => get_messages('results')->{update_success},
        'OK: update success',
    );                                                        # print_and_exit();

    # check 'reported by' & 'authorised by':
    $mech->has_tag_like(
        p => qr(Reported by),
        'OK: reporter information displayed'
    );                                                       # print_and_exit();

    # check result_summary has appended info:
    my $rs_result = "$result_summary_option. $result_summary_expansion"; # warn $rs_result;
    $mech->text_like( # doesn't work - WTF??
        qr($rs_result),
        'OK: result summary has been expanded',
    );                                                        # print_and_exit();

    # can turn 'authorise' flag on & off in config file:
    my $is_authorised = $yaml->{$screening_terms[0]}->{authorise};
    if ($is_authorised) {
        $mech->has_tag_like(
            p => qr(Authorised by),
            'OK: authoriser information displayed'
        );													 # print_and_exit();
    }
    else {
        $mech->content_lacks(
            'Authorised by',
            'OK: lacks authoriser information'
        );
    }                                                        # print_and_exit();
}

# result summary expansion doesn't get re-appended:
$mech->get_ok('/result/=/3');                                 # print_and_exit();
{
    $mech->form_name('molecular_results');
    $mech->tick('complete_all_tests', 1, 1);
    $mech->submit();                                          # print_and_exit();
    $mech->content_lacks(
        "$result_summary_expansion. $result_summary_expansion", # if text re-applied
        'OK: result summary expansion not re-appended on re-submission',
    );                                                        # print_and_exit();
}

# register new:
$mech->get_ok('/request/add_new/2');
{
    $mech->submit_form(
        fields => {
            request_number => 4,
            specimen => 'PB',
            referrer_code => 'C1234567',
        },
    );                                                        # print_and_exit();

    $mech->has_tag(
        h3 => 'New request successful',
    );
}

# screen another request with auto-reportable term:
$mech->get_ok('/screen/=/4');                                 # print_and_exit();
{
    $mech->form_name('initialScreen'); # 1st one is patient notes

    $mech->field(screen_id => 4);
    $mech->field(option_id => 1);
    $mech->submit();                                          # print_and_exit();

    $mech->text_contains(
        "Screened as Follow-up CML (PB)",
        'OK: expected screen term found',
    );
}														     # print_and_exit();

# section result summary should trigger auto-report/authorisation:
$mech->get_ok('/result/=/4');                                 # print_and_exit();
{
	my $result_summary = "BCR-ABL transcription number = 200\n"
	. "ABL transcription number = 20\n"
	. "BCR-ABL : ABL ratio = 2%";

    $mech->form_name('molecular_results');
    $mech->field(results_summary => $result_summary);
	$mech->tick('complete_all_tests', 1, 1);

    $mech->submit();                                          # print_and_exit();

    $mech->has_tag_like(
        p => get_messages('results')->{update_success},
        'OK: update success',
    );                                                        # print_and_exit();

    my @terms = ('Awaiting final diagnosis', 'BCR-ABL transcription number',
        'See RQ PCR result');
    $mech->text_contains(
		$_,
		"OK: expected entry '$_' present",
	) for @terms;                                             # print_and_exit();

    # check 'reported by' & 'authorised by':
    $mech->has_tag_like(
        p => qr(Reported by),
        'OK: reporter information displayed'
    );
}

$mech->get_ok('/history/=/4');                                # print_and_exit();
{
	for ('reported', 'new Molecular result summary') {
		$mech->has_tag_like(
			td => qr($_),
			'OK: expected history present'
		);
	}
}
do_logout();
}
