#!/usr/bin/perl

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

use Data::Dumper;

use strict;
use warnings;

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

=begin: tests:
1) add new flow_details test to lab_tests
2) screen request to generate lab_tests
3) get results page for screened request
4) set test status to 'setup', then re-request lab-test:
5) edit flow_details
6) delete flow details
7) submit flow result summary
8) check for new result summary in history file
9) edit flow result summary
10) check history file
11) delete flow result summary
12) check history file
13) request histology single tests & enter results
14) delete result
15) sign out all section tests
=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 $@;

my $dbix = get_dbix();

# do screen to generate lab_tests:
{
    $mech->get_ok('/screen/=/1');                          # print_and_exit();
    $mech->text_contains(
       'Initial Screen',
        'OK: screen menu loaded',
    );                                                        # print_and_exit();
    
    $mech->form_name('initialScreen'); # 1st one is patient notes

    $mech->field(screen_id => 1);
    $mech->field(option_id => 1);
    $mech->submit();                                          # print_and_exit();
    
    $mech->text_contains(
        'Screened as AML',
        'OK: screen action succeeded',
    );
    
    foreach (qw/AML APML/ ) { # AML HIV PNH 'Flow details'
        $mech->has_tag_like(
            span => qr($_:),
            'OK: expected lab test requested',
        );
    }                                                         # print_and_exit();
    foreach (qw/CML PNH HIV/) { 
        test_out( 'not ok 1 - foo' );
        test_fail( +1 );
        $mech->has_tag_like( span => qr($_), 'foo' );
        test_test( 'OK: expected lab test not requested' );
    }
}

# get results page:
$mech->get_ok('/result/=/1');                                 # print_and_exit();
{
    foreach ( qw/AML APML/ ) {
        $mech->has_tag(
            span => "$_ (new)",
            'OK: requested test detected',
        );
    }
    
    my $str = '<input type="checkbox" name="test_id"\s+value="%s" />';
    foreach (2,5) { # AML, APML
        my $var = sprintf $str, $_;
        $mech->content_like(
            qr($var),
            'OK: outstanding test highlighted',
        );
    }                                                          # print_and_exit();
    
    foreach (1,3,4) { # PNH, CML, HIV
        my $var = sprintf $str, $_;
        $mech->content_lacks(
            $var,
            'OK: not outstanding test not highlighted',
        );
    }                                                         # print_and_exit();

    # flow section - select another test (CML):
    $mech->form_name('flow_requests');
    
    $mech->tick('test_id', 3, 1);
    $mech->submit();                                          # print_and_exit();

    foreach (qw/AML CML APML/) { # still has APML (molecular section)
        $mech->has_tag(
            span => "$_ (new)",
            'OK: expected lab test outstanding',
        );
    }                                                         # print_and_exit();
}

# set test status to 'setup', then re-request lab-test:
{
    $mech->get_ok('/worklist/select?lab_section_id=1');      #  print_and_exit();

    $mech->form_name('display');
    $mech->click_button( value => 'Data Entry');              # print_and_exit();

    $mech->form_name('update_results');

    $mech->field( user_id => 1 );
    $mech->field( status_option_id => 4 ); # setup
    # check one test:
    $mech->tick('request_lab_test_id', 3); # CML

    $mech->submit();                                          # print_and_exit();
    
    $mech->has_tag(
        p => 'INFO: records updated successfully',
        'OK: expected success message received',
    );
    
    # check status
    $mech->has_tag(
        td => 'setup', 
        'OK: expected status detected',
    );                                                        # print_and_exit();

    $mech->get_ok('/result/=/1');                             # print_and_exit();
 
    $mech->has_tag(
        span => 'CML (setup)',
        'OK: expected test status detected',
    );                                                        # print_and_exit();
    
    # check history:
    $mech->get_ok('/history/=/1');                            # print_and_exit();
    $mech->has_tag(
        td => 'set CML status to setup',
        'OK: expected history detected',
    );
    
    # flow section - re-request CML:
    $mech->get_ok('/result/=/1');                             # print_and_exit();
    $mech->form_name('flow_requests');
    
    $mech->tick('test_id', 3, 1);
    #$mech->field('AML partial panel' ),
    $mech->submit();                                          # print_and_exit();    
    
    # check history:
    $mech->get_ok('/history/=/1');                            # print_and_exit();
    $mech->has_tag(
        td => 're-requested CML',
        'OK: expected history detected',
    );                                                        # print_and_exit();
}

# edit flow details:
$mech->get_ok('/result/=/1');                                 # print_and_exit();
{
    my $str = 'AML partial panel';
    
    $mech->content_contains(
        $str, 'OK: expected section_notes detected'
    );                                                        # print_and_exit();
    
    my $new_str = "$str not required";
    $mech->form_name('flow_requests');
    $mech->field('section_notes' => $new_str);
    $mech->submit();                                          # print_and_exit();
    
    $mech->get('/result/=/1');                                
    $mech->content_contains(
        $new_str, 'OK: amended section_notes detected'
    );                                                        # print_and_exit();
    $mech->content_contains(
        $str, 'OK: old section_notes not detected'
    );                                                        # print_and_exit();
    
    # check history:
    $mech->get_ok('/history/=/1');                            # print_and_exit();
    $mech->has_tag(
        td => 'updated Flow section notes',
        'OK: expected history found',
    );
}

# delete flow details:
{
    $mech->get('/result/=/1');                                # print_and_exit();
    
    $mech->form_name('flow_requests');
    $mech->field('section_notes' => undef);
    $mech->submit();                                          # print_and_exit();
    
    $mech->get('/result/=/1');                                # print_and_exit();                             

    $mech->content_lacks(
        'AML partial panel not required',
        'OK: deleted content not detected',
    );
    
    # check history:
    $mech->get_ok('/history/=/1');                            # print_and_exit();
    $mech->has_tag(
        td => 'deleted Flow section notes',
        'OK: expected history found',
    );
}

# submit flow result summary:
$mech->get_ok('/result/=/1');                                 # print_and_exit();
{
    $mech->form_name('flow_results');
    $mech->field(_results_summary => 'drop-down menu entry');
    $mech->field(results_summary => 'textbox entry');
    $mech->submit();                                          # print_and_exit();
    
    $mech->has_tag(
        td => 'drop-down menu entry textbox entry', # new line ignored in HTML
        'OK: expected result summary string found',
    );
}

# check for new result summary in history file:
$mech->get_ok('/history/=/1');                                # print_and_exit();
{
    $mech->has_tag(
        td => 'new Flow result summary',
        'OK: new result summary in history file'
    );
}

# edit flow result summary:
$mech->get_ok('/result/=/1');                                 # print_and_exit();
{
    my $new_text = 'Initial text only.';
    
    $mech->form_name('flow_results');
    $mech->field(results_summary => $new_text);
    $mech->submit();                                          # print_and_exit();

    $mech->has_tag(
        td => $new_text,
        'OK: amended result summary string found',
    );
    
    test_out( 'not ok 1 - foo' );
    test_fail( +1 );
    $mech->has_tag( td => 'Initial text; Normal', 'foo' );
    test_test( 'OK: original result summary string not found' );
}

# check history file:
$mech->get_ok('/history/=/1');                                # print_and_exit();
{
    $mech->has_tag(
        td => 'updated Flow result summary',
        'OK: result summary update in history file'
    );
}

# delete flow result summary:
$mech->get_ok('/result/=/1');                                 # print_and_exit();
{ 
    $mech->form_name('flow_results');
    $mech->field(results_summary => undef);
    $mech->submit();                                          # print_and_exit();

    test_out( 'not ok 1 - foo' );
    test_fail( +1 );
    $mech->has_tag_like( td => qr(Initial text), 'foo' );
    test_test( 'OK: original result summary string not found' );
}

# check history file:
$mech->get_ok('/history/=/1');                                # print_and_exit();
{
    $mech->has_tag(
        td => 'deleted Flow result summary',
        'OK: result summary delete in history file'
    );
}

# request histology single tests & enter results:
$mech->get_ok('/result/=/2');                                 # print_and_exit();
{
    $mech->form_name('histology_requests');
    
    # request CD20, p53 & Mib1 tests:
    foreach (6,7,8) {
        $mech->tick('test_id', $_, 1);
    }
    $mech->submit();                                          # print_and_exit();
    
    foreach ( qw/CD20 p53 Mib1/ ) {
        $mech->has_tag(
            span => "$_ (new)",
            'OK: reqeusted test name detected',
        );
    }                                                         # print_and_exit();
    
    $mech->get_ok('/result/=/2');                              # print_and_exit();
    
    foreach ( qw/CD20 p53 Mib1/ ) {
        $mech->has_tag(
            span => "$_ (new)",
            'OK: requested test name detected',
        );
    }
    
    # enter results for CD20 (subjective) & Mib1 (numeric):
    $mech->form_name('histology_results');
    
    $mech->field( 'lab_test_id_6', '+'); # CD20
    $mech->field( 'lab_test_id_8', '50'); # Mib1
    $mech->submit();                                          # print_and_exit();
    
    $mech->has_tag(
        p => 'INFO: results data update successful',
        'OK: results update success message',
    );
    
    $mech->get('/result/=/2');                                # print_and_exit();
    $mech->form_name('histology_results');

    # check expected results:
    is( $mech->value('lab_test_id_6'), '+', 'OK: expected test result found' );
    is( $mech->value('lab_test_id_8'), '50', 'OK: expected test result found' );
 
    # clear CD20 result:
    $mech->field( 'lab_test_id_6', ''); 
    $mech->submit();                                          # print_and_exit();
    
    $mech->has_tag(
        p => 'INFO: results data update successful',
        'OK: results update success message',
    );

    $mech->get('/result/=/2');                                # print_and_exit();
    $mech->form_name('histology_results');

    # check expected results:
    is( $mech->value('lab_test_id_6'), '', 'OK: expected test result found' );
    is( $mech->value('lab_test_id_8'), '50', 'OK: expected test result found' );
}

# sign out all section tests:
$mech->get_ok('/search/=/2');                                 # print_and_exit();
{   my $i = 1; # warn $mech->text;
    # all tests 'pending':
    foreach ( qw/CD20 Mib1 p53/ ) {
        $mech->text_contains(
            "$_: [pending]",
            "OK: test status 'pending' found [$i]",
        ); $i++;
    }

    $mech->get_ok('/result/=/2');                             # print_and_exit();

    $mech->form_name('histology_results');
    $mech->tick('complete_all_tests', 1, 1);
    $mech->submit();                                          # print_and_exit();

    $i = 1;
    # all tests 'complete':
    foreach ( qw/CD20 Mib1 p53/ ) {
        $mech->content_like( # format changed - success goes to results page now, not view page:
#            qr(<span class="test_name">$_:</span>\s+<span class="test_value">ADMIN</span>),
            qr{<span class="normal">\s+$_ \(ADMIN\)</span>},
            
            "OK: test status 'complete' found [$i]",
        ); $i++;
    }                                                          # print_and_exit();
    
    # check history:
    $mech->get_ok('/history/=/2');                            # print_and_exit();
    $mech->has_tag(
        td => 'set Histology section tests status to complete',
        'OK: expected history found',
    );    
}

# new result summary - drop-down only

# new histology result summary - text-box only

# resubmit same form unaltered - test for no change in history:
$mech->get('/result/=/1');                                    # print_and_exit();
{
    $mech->submit();                                         #  print_and_exit();
    $mech->get('/history/=/1');                               #  print_and_exit();
    
    SKIP: {
        skip('TODO: count number of rows in history table - should be 8 only',1);
    }
}

# request new panel for section configured to expand panels to lab-tests:
{ # register 1 new panel and 2 new lab-tests for Molecular section:
    $dbix->insert('lab_tests', {
        field_label => 'FCL', lab_section_id => 3, test_type => 'panel',
        has_results => 'no', is_active => 'yes', test_name => 'fcl',
    });
    my $test_id = get_last_insert_id('lab_tests');
    $dbix->insert('lab_tests', {
        field_label => 'FCL-Test-1', lab_section_id => 3, test_type => 'test',
        has_results => 'no', is_active => 'yes', test_name => 'fcl_t1',
    });
    _do_panel_lab_test($test_id);
    
    $dbix->insert('lab_tests', {
        field_label => 'FCL-Test-2', lab_section_id => 3, test_type => 'test',
        has_results => 'no', is_active => 'yes', test_name => 'fcl_t2',
    });
    _do_panel_lab_test($test_id);    
    
    $mech->get('/result/=/1');                                # print_and_exit();
    $mech->form_name('molecular_requests');
    $mech->tick(test_id => $test_id);
    $mech->submit();                                          # print_and_exit();

    foreach ( qw/FCL-Test-1 FCL-Test-2/ ) {
        $mech->has_tag(
            span => "$_ (new)",
            "OK: expected test status for $_",
        );
    }
    # does NOT contain original FCL panel request:
    test_out( 'not ok 1 - foo' );
    test_fail( +1 ); # tests next line - must NOT be comment:
    $mech->has_tag_like( span => 'FCL:', 'foo' ); # fails OK, but below should work!!
    # $mech->text_contains( 'FCL: [pending]', 'foo' ); # doesn't fail - WTF???
    test_test( 'OK: selected panel not requested' );
}

do_logout();

sub _do_panel_lab_test {
    my $panel_test_id = shift;
    my $lab_test_id = get_last_insert_id('lab_tests');
    
    $dbix->insert( 'panel_lab_test',
        { panel_test_id => $panel_test_id, lab_test_id => $lab_test_id });
}