package LIMS::Controller::Admin::Config::OutreachPractices;

use base 'LIMS::Base';
use LIMS::Local::Sugar;
use Data::Dumper;

use Moose;
	with (
		'LIMS::Controller::Roles::Misc', # get_blood_tube_type()
	);
__PACKAGE__->meta->make_immutable(inline_constructor => 0);

__PACKAGE__->authz->authz_runmodes( ':all' => 'do_admin' );

# class doesn't handle errors; only valid actions are to insert new row with
# pre-determined value, or delete existing row - no relevant submissions errors
#-------------------------------------------------------------------------------
startmode default { 
    $self->_debug_path($self->get_current_runmode);

    { # get all outreach practices:
        my $data = $self->model('Outreach')->get_outreach_practices;
        
        # extract & add post_code info:
        for (@$data) {
            my $address = $_->{display_name};
            my @addr = split ', ', $address;
            $_->{post_code} = $addr[-1]; # last entry
        }
        $self->tt_params( practices => $data );
    }   
    
    { # callback for default blood-tube-type:
        $self->tt_params( tube_type => sub { $self->get_blood_tube_type(@_) } );
    }

    return $self->tt_process;
}

# -------------------------------------------------------------------------------------
runmode edit ($id) {
    $self->_debug_path($self->get_current_runmode);

    $id || return $self->error('no id passed to '.$self->get_current_runmode);  # $self->debug('id:'.$id);

    my $data = $self->model('Outreach')->get_practice_blood_tube($id)->as_tree;
    { # get post-code data:
        my $address = $data->{display_name};
        my @addr = split ', ', $address;
        $data->{post_code} = $addr[-1]; # last entry
    }
    $self->tt_params( data => $data );

    { # callback for default blood-tube-type:
        $self->tt_params( tube_type => sub { $self->get_blood_tube_type(@_) } );
    }
    return $self->tt_process();
}

#-------------------------------------------------------------------------------
runmode update ($id) { 
    $self->_debug_path($self->get_current_runmode);

    my $vars = $self->query->Vars(); # warn Dumper $vars;
    $vars->{practice_id} = $id;
    
    my $rtn = $self->model('Outreach')->update_practice_blood_tube($vars);
    
    return $rtn
        ? $self->error($rtn)
        : $self->redirect( $self->query->url . '/config/outreach-practices' );
}

1;