package LIMS::Controller::Admin::Config::GeneralPractitioners;

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

use LIMS::Local::ExcelHandler;

use Moose;
	with (
		'LIMS::Controller::Roles::SearchConstraint',
		'LIMS::Controller::Roles::ReferrerSearch',
	);

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

# ------------------------------------------------------------------------------
startmode default ($errs) {
    $self->_debug_path($self->get_current_runmode);
	return $self->tt_process($errs);
}

# ------------------------------------------------------------------------------
runmode search {
	$self->_debug_path($self->get_current_runmode);
	# function located in LIMS::Controller::Roles::ReferrerSearch:	
	return $self->referrer_search('practitioners');
}

# ------------------------------------------------------------------------------
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('Referrer')->get_practitioner_data($id);

    $self->tt_params( data => $data	);

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

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

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

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

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

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

	$data->{id} = $id;

    my $rtn = $self->model('Referrer')->update_general_practitioner($data); # $self->debug($data);

    return $rtn ?
        $self->error($rtn) :
            $self->redirect( $self->query->url . '/config/general-practitioners' );
}

# ------------------------------------------------------------------------------
# regenerate GP table, reading egpcur list for practice codes in referral_sources:
runmode regenerate {
    $self->_debug_path($self->get_current_runmode);

    my $xl = LIMS::Local::ExcelHandler->new(); # $self->debug($xl);
    $xl->source('GP');

    # get referral_types.id for practitioner from referral_types
    my $referral_type = $self->model('Referrer')->get_referral_type('practitioner');

	# get ref to array of all rows in egpcur.csv:
	my $general_practitioners = $xl->fetch_all;

    my $hospital_department = LIMS::DB::HospitalDepartment->new(
        display_name => 'General Medical Practice'
    )->load;

    my $referral_sources
        = $self->model('ReferralSource')->get_referral_sources_by_type;

    # arrayref of practices objects:
    my $referral_source_practices = $referral_sources->{practices};

	# get list of practice_codes in referral_sources table
	my @practice_codes = map {
        $_->organisation_code;
    } @$referral_source_practices;

    # create map of organisation_code => parent_organisation_id:
    my %parent_organisation_id_map = map {
        $_->organisation_code => $_->parent_organisation_id;
    } @$referral_source_practices; # $self->debug(\%parent_organisation_id_map);
	my @gps;

	ROW:
	foreach my $row (@$general_practitioners) { # warn Dumper $row; next;
		# skip row unless $row->{practice_code} matches entry in @practice_codes:
		next ROW unless grep { $row->{practice_code} eq $_ } @practice_codes;

        my $practice_code = $row->{practice_code};

		my %data = (
			name             => $row->{name},
			national_code    => $row->{code},
			practice_code    => $practice_code,
            referral_type_id => $referral_type->id,
            hospital_department_code => $hospital_department->id,
            parent_organisation_id   => $parent_organisation_id_map{$practice_code},
		);

		push @gps, \%data;
	}

	my $rtn = $self->model('Referrer')->regenerate_general_practitioners(\@gps);

    return $rtn ?
        $self->error($rtn) :
            $self->redirect( $self->query->url . '/config/general-practitioners' );
}

1;