package LIMS::Controller::Admin::Config::Clinicians;

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

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

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

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

	my $referral_types = $self->model('Referrer')->get_referral_types;
	my $departments    = $self->model('Referrer')->get_hospital_departments;

    $self->tt_params(
		departments    => $departments,
		referral_types => $referral_types,
	);

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

    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('clinicians');
}

# ------------------------------------------------------------------------------
runmode add_new ($errs) {
	$self->_debug_path($self->get_current_runmode);

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

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

	# get location object from referral_source_id:
	my $location = $self->model('ReferralSource')->get_referral_source($data->{referral_source_id})
	|| return $self->error('cannot retrieve location in '.$self->get_current_runmode);

	# get clinician object or return to start page (flash message set in _get_clinician):
	my $clinician = $self->_retrieve_or_create_clinician($data) # $self->debug($clinician);
	|| return $self->forward('default'); # forward not redirect to retain query params

	my %data = (
		referrer_id              => $clinician->id,
		parent_organisation_id   => $location->parent_organisation_id,
		hospital_department_code => $data->{hospital_department_code},
	);

	# test for existence of referrer_id & organisation_code:
	if ( $self->model('Referrer')->get_referrer_parent_organisation(\%data) ) {
		my $msg = $self->messages('admin')->{clinician}->{not_unique};
		$self->flash( warning => $msg );
		return $self->forward('default');
	}

	# add new referrer_department entry (returns error if not unique entry):
	my $rtn = $self->model('Referrer')->update_referrer_department(\%data);

	if ($rtn) { # $self->debug($rtn);
		return $self->error($rtn);
	}
	else {
		$self->flash( info => $self->messages('admin')->{clinician}->{create_success} );
		return $self->forward('default');
	}
}

# ------------------------------------------------------------------------------
runmode edit ($errs, $id) {
	$self->_debug_path($self->get_current_runmode); # $self->stash(errs => $errs);
	
    $id || return $self->error('no id passed to '.$self->get_current_runmode);  # $self->debug('id:'.$id);

    my $data = $self->model('Referrer')->get_referrer_departments($id);

	my $referral_types = $self->model('Referrer')->get_referral_types;
	
    $self->tt_params(
		data  => $data,
		types => $referral_types,
	);

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

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

# ------------------------------------------------------------------------------
runmode location ($id) { # just sets 'is_active' to yes or no - don't need validation
    $self->_debug_path($self->get_current_runmode);

    # get *clinician id* from app param:
    $id || return $self->error('no id passed to '.$self->get_current_runmode);  # $self->debug('id:'.$id);

    my $vars = $self->query->Vars;
    
    # get *referrer_department id* & is_active from form params:
    my %args = map +($_ => $vars->{$_}), qw( id is_active ); # warn Dumper \%args;
    
    my $rtn = $self->model('Referrer')->update_referrer_department(\%args);
    return $rtn
        ? $self->error($rtn)
        : $self->redirect_after_edit_success('/config/clinicians/edit/' . $id);
}

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

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

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

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

    my $rtn = $self->model('Referrer')->update_clinician($data); # warn $rtn;

    if ($rtn) {
        return $self->error($rtn);
	}
	else {
		# set flash success message:
		$self->flash( info => $self->messages('admin')->{clinician}->{edit_success} );
        $self->redirect( $self->query->url . '/config/clinicians' );
	}
}

# ------------------------------------------------------------------------------
sub _retrieve_or_create_clinician {
	my $self = shift; $self->_debug_path();
	my $data = shift; # warn Dumper $data;

	my $national_code = $data->{prefix} . $data->{national_code};
	my $clinician = $self->model('Referrer')->get_clinician_speculative($national_code);
	my $initials = join '',
		grep { defined $_ }
		map { $data->{'initials_' . $_} } (1..4); # warn $initials;
	
	# if clinician exists, check submitted surname + initials matches clinician object:
	if ($clinician) {
        my $new_clinician_name = join ' ', $data->{surname}, $initials;

		unless ( lc $clinician->name eq lc $new_clinician_name ) {
			my $msg = sprintf $self->messages('admin')->{clinician}->{name_mismatch},
				$national_code, $clinician->name;
			$self->flash( warning => $msg );
			return 0; # triggers return to default start mode
		}
	}
	# else create one:
	else {
		my %clinician = (
			surname  => $data->{surname},
			initials => $initials,
			national_code => $national_code,
		);

		$clinician = $self->model('Referrer')->create_new_clinician(\%clinician);

        if (! $clinician) {
			my $msg = $self->messages('admin')->{clinician}->{failure};
			$self->flash( warning => $msg );
        }
	}

	return $clinician;
}

1;