package LIMS::Local::Search;

use LIMS::Local::Utils ();
use LIMS::Local::Debug;

use DateTime; DateTime->DefaultLocale('en_GB'); # set default locale
use Data::Dumper;

use Moose;
use namespace::clean -except => 'meta';

has query => (
	is  	=> 'ro',
	isa 	=> 'HashRef', # don't specify - can be [Str] or [HashRef]
	default => sub { {} },
	traits  => ['Hash'],
	handles => { set_query => 'set' },
);
# needs to be writable (_process_sql_simple_search() needs to delete keys):
has form_fields => ( is  => 'rw', isa => 'HashRef', required => 1 );

__PACKAGE__->meta->make_immutable;

#-------------------------------------------------------------------------------
sub generate_query {
    my $self = shift;

    my $params = $self->form_fields; # warn Dumper $params;

	# process sql_simple_search params if supplied:
	if ( my $field = $params->{sql_simple_search} ) {
		$self->_process_sql_simple_search($field);
	}
	
    if ( grep $params->{$_}, qw(day month year) ) {
        # create dob as DT object:
        my $dob = DateTime->new( map { $_ => $params->{$_} } qw(day month year) );
        $params->{dob} = $dob->ymd; # $self->debug($dob);
        # delete source keys or 'year' will clash with lab_number:
        map { delete $params->{$_} } qw(day month year);
    }
	
	while ( my($field_name, $search_term) = each %$params ) {
		next unless $search_term; # skip if field empty

        # referrer name search:
        if ( $field_name eq 'referrer_name' ) {
            # converts comma/spaces to single space for GP's & clinicians format:
            $search_term =~ s/[\,\s]+/ /;
			$self->set_query( name => { like => $search_term . '%' } );
        }        
        # first_name/last_name/name search:
        elsif ( $field_name =~ /name\Z/ ) { # \A(first|last)_name\Z
            # enable 'like' queries on names:
			$self->set_query( $field_name => { like => $search_term . '%' } );
        }
        # lab_number search:
        elsif ( $field_name eq 'lab_number' ) {
			my ($request_number, $year)
				= LIMS::Local::Utils::split_labno( $search_term );
			$self->set_query( request_number => $request_number );
			$self->set_query( year => $year );
        }
        # nhs_number search:
        elsif ( $field_name eq 'nhs_number' ) {
            # collapse spaces if submitted in nnn nnn nnnn format:
            $search_term =~ s/\s+//g;
			$self->set_query( nhs_number => $search_term );
        }
		# request options:
        elsif ( grep $field_name eq $_, qw(private urgent copy_to) ) {
            # need to map option_ids ??
        }
        # wildcard search:
        elsif ( $search_term =~ /[\%\*]/ ) {
            # substitute * for sql wildcard:
            $search_term =~ s/\*/\%/;
			$self->set_query( $field_name => { like => $search_term } );
        }        
        # everything else:
        else {
			$self->set_query( $field_name => $search_term );
        }
    }

	return $self->query;
}

#-------------------------------------------------------------------------------
sub _process_sql_simple_search {
    my ($self, $search_field) = @_;
	
    my $params = $self->form_fields;
	
	my $logic = $params->{logic}; # MATCHES, CONTAINS, LACKS, etc
	my $search_term = $params->{kwd};

=begin # TODO - could allow AND / OR in search term (need to ensure rels load for AND):
foo => { like => [ '%bar%', '%baz%' ] }, # foo LIKE '%bar%' OR foo LIKE '%baz% 
and => [ foo => { like => 'bar' }, foo => { like => 'baz'} ], # foo LIKE '%bar%' AND foo LIKE '%baz% 
=cut

	my $constraints_map = {
		BEGINS   => { like => $search_term . '%' },
		ENDS     => { like => '%' . $search_term },
		CONTAINS => { like => '%' . $search_term . '%' },
		LACKS    => { 'not like' => '%' . $search_term . '%' },
		MATCHES  => $search_term,
	};	
	
	# get constraint expression for required logic:	
	my $query_constraint = $constraints_map->{$logic};

	$self->set_query( $search_field => $query_constraint );

	# delete these keys so generate_query() doesn't choke on them:
	map { delete $params->{$_} } qw(sql_simple_search logic kwd);
}

1;