package LIMS::Controller::Roles::ReferrerSearch;

use strict;
use Moose::Role;

sub referrer_search {
    my ($self, $referrer_type) = @_; # warn $referrer_type;
    
	my $dfv = $self->check_rm('default', $self->validate('referrer_search') )
	|| return $self->dfv_error_page;

    my $data = $dfv->valid
    || return $self->forward('default'); # eg if empty param
    
    my $search_terms = $self->generate_search_constraints($data)
    || return $self->forward('default'); # protect against submission of empty form

    my %args_for_count = (
        search_terms  => $search_terms,
        referrer_type => $referrer_type,
    );
    
    my $total_count
        = $self->model('Referrer')->get_referrer_count(\%args_for_count);
    #  $self->debug($total_count);
	
    # zero hits, or too many to handle:
    if (! $total_count || $total_count > 1000 ) {
        $self->stash->{status_msg} = $total_count ?
            sprintf $self->messages('search')->{too_many_records}, $total_count
                : $self->messages('search')->{no_records_found};

        my $html = $self->forward('default');
        return $self->fill_form($html);
    }

    my %args_for_search;
    if ( $total_count > $self->cfg('settings')->{entries_per_page} ) {
        # invoke pager for template and add limit & offset params to \%args:
        $self->pager({ query => \%args_for_search, total => $total_count });
    }
	
	my $referrers
        = $self->model('Referrer')->get_referrers($search_terms, \%args_for_search);
	
	$self->tt_params( referrers => $referrers );
	
	return $self->tt_process;
}

=begin # using referrer_department.parent_organisation rel in model now
sub _get_address_map {
    my $self = shift;
    my $referrers = shift;

    # get list of referrer.id's from referrers object:
    my @referrer_ids = map { $_->id } @$referrers; # DEBUG \@request_ids;

	my $referrer_departments
		= $self->model('Referrer')->get_practice_addresses(\@referrer_ids);
	
    # create address_map of keys = referrer_id, vals = parent_org.description
    my %address_map;
    foreach my $r( @{ $referrer_departments } ) {
		my $referrer_id = $r->referrer_id;
        my $address  = $r->parent_organisation->description;
		$address_map{$referrer_id} = $address;
    }

    return \%address_map;
}
=cut

1;