package LIMS::Controller::Roles::SearchConstraint;

use Moose::Role;
use LIMS::Local::Search;

sub generate_search_constraints { 
    my ($self, $data) = @_; # $self->debug($data);

    # need to do specimen code lookup if search includes specimen:
    if ( my $specimen_code = $data->{specimen_code} ) { # warn $sample_code;
        $data->{specimen_id}
            = $self->model('Specimen')->get_specimen_id($specimen_code);
        # delete specimen_code key - no field to match against:
        delete $data->{specimen_code};
    }

    my $user_profile = $self->user_profile;
    
    # args for search object:
    my %args = (
        form_fields  => $data,
        user_profile => $user_profile,
    );

    # create search object:
    my $search = LIMS::Local::Search->new(\%args);

    # generate query from form fields as hashref:
    my $query = $search->generate_query; # $self->debug($query);

    if (%$query) {
        return $query; # return hashref
    }
    else {
        $self->stash->{error_msg} = $self->messages('search')->{empty_submission};
        return 0;
    }
}

sub quick_search_constraints {
    my ($self, $var) = @_; # $self->debug($var);
    
    # create hash in case multiple keys, then return array(ref):
    my %data;
    
    # all numbers = nhs number or patient number:
    if ( $var =~ /^\d+$/ ) {
        $data{unit_number} = $var;
        $data{lab_ref} = $var if length $var < 6;
        $data{nhs_number} = $var if length $var == 10;
    }
    # alphabetic probably name(s):
    elsif ( $var =~ /\w+/ ) {
        # all one word (with hyphen or apostrophe):
        if ( $var =~ /^(\w|-|\')+$/ ) {
            $data{first_name} = $var;
            $data{last_name}  = $var;
        }
        # comma separated:
        elsif ( my ($cs1, $cs2) = split /,\s?/, $var ) {
            $data{last_name}  = $cs1;
            $data{first_name} = $cs2;
        }
        # space separated:
        elsif ( my ($ss1, $ss2) = split /\s+/, $var ) {
            $data{first_name} = $ss1;
            $data{last_name}  = $ss2;
        }
        # one or more numbers:
        elsif ( $var =~ /\d+/ ) {
            $data{unit_number} = $var;
        }
    }
    return \%data;
}

1;