package Role::Main;

use Moose::Role;

has trial_id_map => ( is => 'ro', isa => 'HashRef', lazy_build => 1 );
has options_map  => ( is => 'ro', isa => 'HashRef', lazy_build => 1 );

sub do_clinical_trials {
    my $self = shift;
    my $vals = shift;

    my $hilis3_trial_id = $vals->{study} || return;
    
    my $trial_id_map = $self->trial_id_map;
    
    my $hilis4_trial_id = $trial_id_map->{$hilis3_trial_id}
    || die "No hilis4 clinical_trial.id available for $hilis3_trial_id";
    
    my %data = (
        request_id => $vals->{_request_id},
        trial_id   => $hilis4_trial_id,
    );
    $self->db->{dbix4}->insert('request_trial', \%data);
}

sub do_additional_options {
    my $self = shift;
    my $vals = shift;
    
    # urgent, private, copy_to, doi, teaching:
    my $options = $self->options_map;
    
    foreach ( keys %$options ) {
        my $option = $_;
        
        next unless $vals->{$option};
        
        my %data = (
            request_id => $vals->{_request_id},
            option_id  => $options->{$_},
        );
        $self->db->{dbix4}->insert('request_option', \%data);
    }
}

sub _build_options_map {
    my $self = shift;
    
    my $dbh4  = $self->db->{dbix4};
    
    my $options = $dbh4->query( 'select option_name, id from additional_options')->map;
    
    { # 'CopyTo' => 'copy_to'
        my $cc_id = $options->{copy_to};
        delete $options->{copy_to};
        $options->{copyto} = $cc_id;
    }
    
    return $options;
}

sub _build_trial_id_map {
    my $self = shift;
    
    my $dbh3  = $self->db->{dbix3};
    my $dbh4  = $self->db->{dbix4};
    
    my $hilis3_trials = $dbh3->query('select TrialName, id from Trials')->map;
    my $hilis4_trials = $dbh4->query('select trial_name, id from clinical_trials')->map;    
    
    { # 'Community monitoring' changed to 'HMDS outreach'
        my $cmp_id = $hilis3_trials->{'Community monitoring'};
        delete $hilis3_trials->{'Community monitoring'};
        $hilis3_trials->{'HMDS outreach'} = $cmp_id;
    }
    
    # map hilis3 Trials.id => hilis4 clinical_trials.id    
    my %map = map {
        my $hilis3_trial_name = $_; # warn $hilis3_trial_name;
        my $hilis3_trial_id = $hilis3_trials->{$hilis3_trial_name};
        my $hilis4_trial_id = $hilis4_trials->{$hilis3_trial_name};
        
        $hilis3_trial_id => $hilis4_trial_id;
    } keys %$hilis3_trials;
    
    return \%map;
}

1;