package LIMS::Controller::Admin::Config::ReferralSources;

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

use LIMS::Local::ExcelHandler;
use Data::Dumper;

use Moose;
	with (
		'LIMS::Controller::Roles::SearchConstraint',
		'LIMS::Controller::Roles::LocationSearch',		
	);
__PACKAGE__->meta->make_immutable(inline_constructor => 0);
	
__PACKAGE__->authz->authz_runmodes(	':all' => 'do_admin' );

# ------------------------------------------------------------------------------
startmode default ($errs) {
    $self->_debug_path($self->get_current_runmode); # $self->stash(errs => $errs);

    # get js validation foo_onsubmit & foo_dfv_js vars into tt_params:
    $self->js_validation_profile('referral_sources');

	my $data_files = $self->_get_data_files();
	$self->tt_params( data_files => $data_files );

    return $self->tt_process($errs);
}

# ------------------------------------------------------------------------------
runmode search {
    $self->_debug_path($self->get_current_runmode); 
	# function located in LIMS::Controller::Roles::LocationSearch:	
	return $self->referral_source_search;	
}

# ------------------------------------------------------------------------------
runmode edit ($errs, $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('ReferralSource')->get_referral_source($id);
	my $parent_organisations = $self->model('ReferralSource')
		->get_parent_organisations({}, { sort_by => 'description' }); # 1st arg = $search_terms

    $self->tt_params(
        errs => $errs,
		data => $data,
		parent_organisations => $parent_organisations,
	);

    # get js validation foo_onsubmit & foo_dfv_js vars into tt_params:
    $self->js_validation_profile('referral_sources');

    return $self->tt_process($errs);
}

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

	# put id (if submitted) into params() as _record_id for validation:
    if ( $id ) {
		$self->query->param( _record_id => $id ); 
    }

    # if param 'id' passed, return error to edit():
    my $error_rm = $id ? 'edit' : 'default';

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

    my $data = $dfv->valid
    || return $self->forward('default'); # $self->debug($data); # eg if empty param

	# provide 'id' if supplied, so record updated, otherwise new one created: 
	$data->{id} = $id if $id;

    my $rtn = $self->model('ReferralSource')->update_referral_sources($data);

	if ($rtn) {
		return $self->error($rtn);
	}
	else {
		# set success message:
		my $msg = $id ? 'edit_success' : 'create_success';
		$self->flash( info => $self->messages('action')->{$msg} );
        # if we've just created a new practice:
        if ($msg eq 'create_success' && $data->{referral_type} eq 'practice') {
            # update referrers table with GP's for new practice:
            $self->_update_practitioners($data->{organisation_code});
            
            # issue outreach practice warning:
            if ( $self->cfg('settings')->{have_outreach} ) {
                my $msg = $self->messages('admin')->{referral_source}->{outreach};
                $self->flash( warning => $msg );
            }
        }
        
		$self->redirect( $self->query->url . '/config/referral-sources' );
	}
}

# ------------------------------------------------------------------------------
sub _update_practitioners { # code based on A::C::GeneralPractitioners::regenerate()
    my ($self, $practice_code) = @_;
    
    my $xl = LIMS::Local::ExcelHandler->new(); # $self->debug($xl);
    $xl->source('GP');

    my $new_gps = $xl->fetch_cols({
        select => 'practice_code',
        value  => $practice_code,
        fields => [ qw( code name ) ], # gp code, gp name
    });
    
    my $parent_organisation = $self->model('Base')->get_object_by_param({
        class_name   => 'ParentOrganisation',
        column_name  => 'parent_code',
        column_value => $practice_code,
    });
    
    # get 'general practice' entry from hospital_departments table:
    my $hospital_department = $self->model('Referrer')
        ->get_hospital_department('General Medical Practice');
    
    my @data = (); 
    
    for (@$new_gps) {
        my ($national_code, $name) = @$_;
    	my %gp = (
			name             => $name,
			national_code    => $national_code,
			practice_code    => $practice_code,
            referral_type_id => $parent_organisation->referral_type_id,
            hospital_department_code => $hospital_department->id,
            parent_organisation_id   => $parent_organisation->id,
		);
		push @data, \%gp;
	} # warn Dumper @data;
    
	my $rtn = $self->model('Referrer')->regenerate_general_practitioners(\@data);
    if ($rtn) {
        $self->flash( error => $rtn );
    }
    else {
        my $count = scalar @data;
        $self->flash( info => $count . ' new GP\'s added' );
    }
}

# ------------------------------------------------------------------------------
sub _get_data_files {
	my $self = shift;

	my $data = $self->get_yaml_file('cfh_data_files');
	
	my @data_files = keys %$data; # $self->debug(\@data_files);
	return \@data_files;
}

# ------------------------------------------------------------------------------
=begin # can't use numerical values with show/hide javascript
sub _get_referral_types_map {
	my $self = shift;
	
	my $referral_types = $self->model('ReferralSource')->get_referral_types();
	
	my %referral_types_map = map {
		$_->description => $_->id;
	} @$referral_types;
	
	return \%referral_types_map;
}
=cut

1;