package PhotoPub::Search;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(&makesearchre &filteralbum &filterrange);

use strict;

use PhotoPub::Global qw($error);
use PhotoPub::Utils qw($searchstringre);
use PhotoPub::Annots qw(&getannot);

sub makesearchre {
  my $phrase = shift;
  my $ret;

  # CGI:: has unescaped it, we just need to check it's friendly
  unless($phrase =~ /^$searchstringre$/) {
     &$error(type => 'userinput',
              message => "Invalid characters in search request");
  }

  # Logic is quite simple for the time being:
  #    "foo"  "foo or bar"  "foo and bar" are all we handle
  my @ands = ($phrase =~ /\sand\s/g);
  my @ors = ($phrase =~ /\sor\s/g);
  if(scalar(@ands) + scalar(@ors) > 1) {
     &$error(type => 'userinput',
              message => "Search command can only contain a single \"and\" or \"or\"");
  }

  if(scalar(@ands)) {
     my ($a,$b) = ($phrase =~ /^(.*)\sand\s(.*)$/);
     $ret = "($a.*$b)|($b.*$a)";
  } elsif(scalar(@ors)) {
     my ($a,$b) = ($phrase =~ /^(.*)\sor\s(.*)$/);
     $ret = "($a)|($b)";
  } else {
     $ret = "($phrase)";
  } 

  return $ret;
}

sub filteralbum {
  my ($searchre,$items)=@_; 
  my @allitems = @$items;
  @$items = ();
  foreach my $item (@allitems) {
    if($item->{'type'} eq 'group') {
      if($item->{'description'} =~ /$searchre/i) {
	push @$items, $item;
      }
    } elsif($item->{'type'} eq 'link') {
      if($item->{'title'} =~ /$searchre/i) {
	push @$items, $item;
      }
    } elsif($item->{'type'} eq '') {
      # Do nothing
    } else {
      &$error(type=>'internal',
	      message=>"Unsupported item type \"".$item->{'type'}
	      ."\" found when processing search");
    }
  }
}

sub filterrange {
  my ($searchre,$photos)=@_;
  my @allphotos = @$photos;
  @$photos = ();
  foreach my $pic (@allphotos) {
    my $descr=&getannot($pic,'description');
    $descr='' unless defined $descr;
    if($descr =~ /$searchre/i) {
      push @$photos,$pic;
    }
  }
}

1;
