package LIMS::Controller::ReferralSource;

use strict;

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

sub default : StartRunmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    my $location_type = $self->query->param('lookup');

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

    return $self->tt_process;
}

# lookup function for new hospital/practice/GP, etc:
sub lookup : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    my $location_type = $self->query->param('type')
        || return $self->error('no location type passed to '.$self->get_current_runmode);

    my $string = $self->query->param('string')
        || return $self->error('no search string passed to '.$self->get_current_runmode);

    # need min 3 chars to search:
    return unless length $string >= 3;

    my $xl = LIMS::Local::ExcelHandler->new(); # $self->debug($xl);
    $xl->source($location_type);
	
    # array of hashrefs:
    my $matches = $xl->parse($string); # $self->debug($matches);
	my $file_data = $xl->filedata;

=begin # AJAX/xml:
    my $xml = $self->_format_as_xml($matches);

    # set header type to xml:
    $self->header_props(-type=>'text/xml');

    return $xml;
=cut

    foreach my $location (@$matches) {
        $location->{display} =~ s/($string)/$self->query->b($1)/egi;
    }

    $self->tt_params(
        matches       => $matches,
		file_data	  => $file_data,
        location_type => $location_type,
    );

    $self->tt_process('referralsource/default.tt');
}

# -------------------------------------------------------------------------------------
=begin # for ajax function, but too slow for ajax
sub _format_as_xml {
    my $self = shift;
    my $matches = shift;

    my @rs = map {
        sprintf q!<rs id="%s" info="%s">%s</rs>!,
            $_->{code},
            $_->{code},
            $self->query->escapeHTML($_->{display}), # escape eg '&' or output fails
    } @$matches;

    my $results =
        sprintf q!<?xml version="1.0" encoding="utf-8" ?><results>%s</results>!, ( join '', @rs );

    return $results;
}
=cut

1;

