package LIMS::Model::Roles::ScreenUpdate;

use Moose::Role;

has status_option_new => (
    is => 'ro',
    isa => 'LIMS::DB::LabTestStatusOption',
    lazy_build => 1,
);

#-------------------------------------------------------------------------------
# creates new lab_tests according to ScreenLabTest data for this screen_id
# doesn't overwrite existing tests
sub do_lab_tests {
    my $self = shift;
    my $data = shift;
    
    my %args = (
        query => [ screen_id => $data->{screen_id} ],
    );

    my $lab_tests
        = LIMS::DB::ScreenLabTest::Manager->get_screen_lab_tests(%args);

    foreach my $t (@$lab_tests) {
        $data->{lab_test_id} = $t->lab_test_id;
        $self->do_new_lab_test($data);
    }
}

#-------------------------------------------------------------------------------
sub do_new_lab_test { # shared by M::Request::new_request()
    my $self = shift;
    my $data = shift; # requires lab_test_id && user_id
    
    my $status_option = $self->status_option_new;
    
    LIMS::DB::RequestLabTestStatus->new(
        user_id          => $self->user_profile->{id},
        lab_test_id      => $data->{lab_test_id},
        request_id       => $data->{_request_id},
        status_option_id => $status_option->id,
    )->load_or_insert; # in case test already requested manually    
}

#-------------------------------------------------------------------------------
sub do_lab_test_details {
    my $self = shift;
    my $data = shift;
    
    my %args = (
        query => [ screen_id => $data->{screen_id} ],
    );

    my $lab_test_details
        = LIMS::DB::ScreenLabTestDetail::Manager->get_screen_lab_test_details(%args);
    
    foreach my $detail (@$lab_test_details) { # should only be 0 or 1:
        LIMS::DB::RequestLabSectionNote->new(
            details        => $detail->test_details,
            request_id     => $data->{_request_id},
            lab_section_id => $detail->lab_section_id,
        )->load_or_insert; # in case test_detail already exists
    }
}

#-------------------------------------------------------------------------------
sub _build_status_option_new {
    my $self = shift;
    
    my $status_option  
        = LIMS::DB::LabTestStatusOption->new(description => 'new')->load;
        
    return $status_option;
}

1;