package LIMS::Controller::Error;

use base 'LIMS::Base';

use Moose;
	with (
		'LIMS::Controller::Roles::User',
#		'LIMS::Controller::Roles::DataMap'
	);
	
# ------------------------------------------------------------------------------
# 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; # $self->stash( errs => $errs );
	
    return $self->forbidden() unless $self->user_can('log_errors');
    
    my $request_id = $self->param('id')
    || return $self->error('no id passed to ' . $self->get_current_runmode);

	# stash request_id for template:
	$self->stash(request_id => $request_id);

    my $data = $self->model('Request')->get_request_errors($request_id);
	my $error_codes
		= $self->model('ErrorCode')->get_error_code_assignment('errors');
		
    $self->tt_params( 
        data => $data,
		error_codes => $error_codes,
	);

	$self->js_validation_profile('request_error');

    return $self->tt_process('error/default.tt', $errs);
}

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

    my $dfv = $self->check_rm('load', $self->validate('request_error') )
	|| return $self->dfv_error_page;

    my $data = $dfv->valid(); # $self->debug($data);

    # put request_id into $data:
    $data->{request_id} = $request_id;
	
    my $rtn = $self->model('Request')->request_error_code($data);

    if ($rtn) {
        $self->error($rtn);
	}
	else {
		$self->flash( info => $self->messages('action')->{create_success} );
		$self->redirect( $self->query->url . '/error/=/' . $request_id );
	}
}

1;
