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

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

use Data::Dumper;

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);

    my $xl = LIMS::Local::ExcelHandler->new(); # $self->debug($xl);
    $xl->source('GP'); # to display last update of file:
    $self->tt_params( file_data => $xl->filedata );
    
	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:
# open egpcur.csv
# skip rows where practice code IS NOT in referral_sources table
# skip rows where practitioner code IS in referrers table (might want to check
# practice affiliation first)
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 'general practice' entry from hospital_departments table:
    my $hospital_department = $self->model('Referrer')
        ->get_hospital_department('General Medical Practice');
    
#$self->_debug_path('here');
 	# get ref to array of all rows in egpcur.csv:
	my $egpcur = $xl->fetch_all;
#$self->_debug_path('here');

   # get arrayref of all general practice objects:
    my $referral_sources
        = $self->model('ReferralSource')->get_referral_sources_by_type;
    my $referral_source_practices = $referral_sources->{practices};

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

    # get map of all practitioner national_codes in referrers table:
    my $practitioners = $self->model('Referrer')->get_general_practitioners;
    my %practitioner_codes = map { $_->national_code => 1 } @$practitioners;
    
    # 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);
    
#$self->_debug_path('here');
	my @gps = ();
	ROW:
	foreach my $row (@$egpcur) { # warn Dumper $row; next;
        my $practice_code = $row->{practice_code};
        my $gp_code = $row->{code};
        my $gp_name = $row->{name};
        
		# skip row unless practice_code val present in referral_sources table:
		next ROW unless $practice_codes{$practice_code};
        # skip row if GP already exists in referrers table:
        next ROW if $practitioner_codes{$gp_code};
        
		my %data = (
			name             => $gp_name,
			national_code    => $gp_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;
	}
#$self->_debug_path('here'); # warn Dumper @gps;

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

    if ($rtn) {
        return $self->error($rtn);
    }
    else {
        my $count = scalar @gps;
        $self->flash( info => $count . ' new GP\'s added' );
        return $self->redirect( $self->query->url . '/config/general-practitioners' );
    }
}

1;