package LIMS::Controller::Storage;

use Moose;

# if using 'extends', need to run at compile time to load attribute handlers
# from parent class otherwise StartRunmode, Runmode, etc fails - hack around AutoRunmode
BEGIN { extends 'LIMS::Base'; }
with (
	'LIMS::Controller::Roles::RecordHandler',
);

__PACKAGE__->meta->make_immutable(inline_constructor => 0);

use Data::Dumper;

# ------------------------------------------------------------------------------
# default() should never be called direct - redirect to start page:
sub default : StartRunmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    return $self->redirect( $self->query->url );
}

# ------------------------------------------------------------------------------
sub load : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    my $errs = shift;
    
    my $request_id = $self->param('id')
    || return $self->error('no id passed to ' . $self->get_current_runmode);

	# get request data:
    my $request_data = $self->model('Request')->get_single_request($request_id);
	# get existing storage data:
	my $storage      = $self->model('Storage')->get_request_storage($request_id);
	# get list of existing samples in storage
	my %specimens 	 = map { $_->specimen->sample_code => 1 } @$storage;
	# get specimen map for request:
    my $specimen_map = $self->specimen_map([ $request_id ]); # warn Dumper $specimen_map;    
	
    $self->tt_params(
        request_data => $request_data,
        specimen_map => $specimen_map,
		specimens    => \%specimens,
		storage      => $storage,
    );
	return $self->render_view($self->tt_template_name);    
}

# ------------------------------------------------------------------------------
sub input : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    my $errs = shift;
    
    my $request_id = $self->param('id')
    || return $self->error('no id passed to ' . $self->get_current_runmode);

    my $params = $self->query->Vars; warn Dumper $params;
    $params->{request_id} = $request_id;
	
	my $rtn = $self->model('Storage')->input_storage($params);
	
    # insert flash message
    return $self->redirect( $self->query->url . '/storage/=/' . $request_id );
}

# ------------------------------------------------------------------------------
sub output : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    my $errs = shift;
    
    my $request_id = $self->param('id')
    || return $self->error('no id passed to ' . $self->get_current_runmode);

    my %params = $self->query->Vars; warn Dumper \%params;    

    # insert flash message
    return $self->redirect( $self->query->url . '/storage/=/' . $request_id );
}

1;