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

    { # refomat request date and DoB fields:
        my @date_fields = qw(day month year);
        if ( grep $params->{$_}, map 'dob_'.$_, @date_fields ) {
            # create dob as DT object:
            my $dob = DateTime->new( map +($_ => $params->{'dob_'.$_}),
                @date_fields );
            $self->set_query( dob => $dob );
            # delete (invalid) params dob_*:
            map delete $params->{'dob_'.$_}, @date_fields;
        }	
        if ( grep $params->{$_}, map 'request_'.$_, @date_fields ) {
            # create date as DT object:
            my $date = DateTime->new( map +($_ => $params->{'request_'.$_}),
                @date_fields );
            
            # if date_before or date_after flags set:
            if ( my $extend_date = $params->{date_extend} ) {
                my $expr = $extend_date eq 'all_after'
                    ? { ge => $date->ymd } # ie <date> 00:00:00
                    : { le => $date->add(days => 1)->ymd }; # ie <date + 1> 00:00:00
                $self->set_query( created_at => $expr );
                delete $params->{date_extend};
            }
            else { # need to create a 'between' to handle timestamp field:
                $self->set_query( created_at => {
                    gt_le => [ $date->ymd, $date->clone->add(days => 1)->ymd ]
                });
            }
            # delete invalid params request_*:
            map delete $params->{'request_'.$_}, @date_fields;
        }
    }

	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) ) {
            $self->set_query( option_name => $field_name );
        }
        # 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;