package RequestAudit;

use Moose;
    with 'Role::RebuildTables';
	
use namespace::clean -except => 'meta';

use Data::Dumper;

has $_ => (is => 'ro', isa => 'HashRef', required => 1)
	foreach qw( db sql );

has log_file => ( is => 'ro', required => 1 );

__PACKAGE__->meta->make_immutable;

my @tables = qw(
    request_audit
);

$|++;

sub convert {
    my $self = shift;

    my $dbix3 = $self->db->{dbix3};
    my $dbix4 = $self->db->{dbix4};

    my $log_file = $self->log_file;

    $self->rebuild_tables(\@tables);

	my $hilis3 = $dbix3->query(q!select main_id, indication, HMDS, year(Date) as 'year'
        from BoneMarrowAudit left join Main on main_id = DBID!);
	
	my $audit_options_map
        = $dbix4->query('select description, id from audit_request_options')->map;		
	
    # incorrect/missing entries:
    $audit_options_map->{'Anaemia - unspecified'} = $audit_options_map->{Anaemia};
    $audit_options_map->{'Transplant follow-up'} = $audit_options_map->{'Transplant follow up'};
    $audit_options_map->{'Non-Hodgkin\'s Lymphoma staging'}
        = $audit_options_map->{"Non-Hodgkin Lymphoma staging"};
    $audit_options_map->{"Non-Hodgkin\\'s Lymphoma staging"}
        = $audit_options_map->{"Non-Hodgkin Lymphoma staging"};

	ROW:
	while ( my $vals = $hilis3->hash ) { 
		my $request_id = $dbix4->query( q!select id from requests where request_number
			= ? and year = ?!, $vals->{hmds}, $vals->{year} )->list;
		
		if (! $request_id ) {
			# warn "no request_id for $vals->{main_id}";
			next ROW;
		}
		
        my $audit_option = $vals->{indication};
        my $audit_option_id = $audit_options_map->{$audit_option}
        || die "no audit_option_id for '$audit_option'";
        
		my %data = (
			request_id => $request_id,
			audit_request_option_id => $audit_option_id,
		);
		$dbix4->insert('request_audit', \%data);
    }
    $self->convert_to_InnoDB($_) for @tables;
}

1;

