#!/usr/bin/perl

package person;
use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
my $start=[gettimeofday];

use Digest::SHA1 qw(sha1 sha1_hex);
use strict;
use jip;
use Lok;
use Person;
use Data::Dumper;
use CGI;

$|++;
my $q=new CGI;


# we zetten het permanent helemaal uit, deel 1 'verwijder Stas uit de zoekresultaten'
#$q->header(-status => '410 Gone');
#exit(0);


my $not_stas=1;
if ( $q->param('q') eq '7c0210e68b799842401b4e94716b160529146ab5' ){
  $not_stas = 0;
  $q->header(-status => '404 Not Found');
  exit(0);
}

print $q->header;

use Server;
my $server=Server->instance();

my $action  = $q->param('action');
my $cgitmpl = $q->param('tmpl') || 'image-person';

my $qself   = $q->self_url;
my $qselfs  = $q->url;


my $debug=0;
my $msg='';




my $tmpl=$server->gettemplate($cgitmpl);
my $hoofd=hoofd('Mensen');

$tmpl->param( 'actionis_' . $action => $action,
	      'action' => $action,
	       hoofd    => $hoofd,
);



if ( $q->param('q') && $not_stas ){
  my $search= $q->param('q');
  #
  # search images with person
  #
  my $sq=$server->quote($search);
  my ($sth,$err);

  my $codep = {}; # gevonden person hash op nick
  undef $codep    ;
  #
  # zoek eerst op sha1
  #
  my $sha1q="
   SELECT * FROM person as p 
   WHERE 
   mbox_sha1sum =  $sq
  ";
  my ($sth,$err)=$server->doq($sha1q);

  unless ($sth->rows eq 1){
    my $query="
     SELECT * FROM person as p 
     WHERE 
     name ~* $sq 
     OR
     mbox ~* $sq
     OR
     nick ~* $sq
     OR
     foaf ~* $sq
     OR
     surname ~* $sq
    ";
    $msg .=  $query if $debug;
    
    ($sth,$err)=$server->doq($query);
    $msg .= $err if $err;
  }


  #20040910
  unless ($cgitmpl =~ /inner/){
  if ($sth->rows >1){
	$tmpl->param( morethanoneperson => 1);
	print " More than 1 person found. TODO";
        exit;
  }
  }


  $tmpl->param( numperson => $sth->rows,);
  my @persons;
  while (my $row=$sth->fetchrow_hashref){
    push @persons,$row;
  }


  #
  # gevonden personen
  # 

  foreach  ( @persons ){
    my $id=$_->{'id'};

    $_->{'qself'}  = $qself;
    $_->{'qselfs'} = $qselfs;


    
    # zoek plaatjes met persoon
    my $qid=$server->quote($id);
    my $query = "
     SELECT * FROM images as i, rel_image_person as ip
     WHERE i.id=ip.imageid
     AND ip.personid=$qid
     ORDER BY i.filedate desc
    ";
    my ($sth,$err)=$server->doq($query);
    die $err if $err;
    my @is;

    # loop gevonden plaatjes
    while (my $row=$sth->fetchrow_hashref){
      my $imageid=$row->{'imageid'};
      my $image=Lok->new($imageid);
      #print Dumper($imageid);
      #print Dumper($image);
      
      #
      # 20030611, location
      #
      use Location;
      my $loc=Location->new($image->{'row'});
      unless ( $loc->{'lat'} && $loc->{'lon'} ){
	$image->{'row'}->{'nolocation'}=1;
      }else{
	$image->{'row'}->{'haslocation'}=1;
	$image->{'row'}->{'lat'} = $loc->{'lat'};
	$image->{'row'}->{'lon'} = $loc->{'lon'};
	$image->{'row'}->{'locationname'} = $loc->{'locationname'};
      }
      #
      # /location
      #
      
      # personen op plaatje
      my $p=Person->new( { lok => $image, } );
      $image->{'row'}->{'personloop'} = $p;
      # codep
      foreach my $pip ( @{$p} ){
	#print Dumper($pip);
	unless ( $pip->{'nick'} eq $_->{'nick'} ) {
	  $codep->{ $pip->{'nick'} } = $pip;
	}
      }
      # /codep
      # /personen op plaatje
      
      
      push @is,$image->{'row'};
    }
    $_->{'images'}=\@is;


    # coperson
    my @coperson;
    foreach my $pip ( keys %{$codep} ){
      push @coperson, $codep->{ $pip };
    }
    # print "<pre>COPERSON:". Dumper(@coperson);
    $_->{'coperson'} = \@coperson;
    # /coperson



  } # / loop gevonden person
  
  #
  # /search images with person
  #
  
 

  #
  # search images with word
  #
  

  my $query="
   SELECT distinct(word) FROM rel_image_word
   WHERE word ~* $sq
   GROUP BY word
   ORDER BY word
  ";
  # print $query;
  my ($sth,$err)=$server->doq($query);
  print $err if $err;
  my @words;
  while (my $row = $sth->fetchrow_hashref){
    #print Dumper($row);
    push @words,$row;
  }
  foreach (@words){
    ($_->{'sword'}) = $_->{'word'} =~ m!.*\/(.*)$!;
    my $qword=$server->quote( $_->{'word'} );
    my $query="
     SELECT DISTINCT(about) 
     FROM rel_image_word
     WHERE word = $qword
    ";
    my ($sth,$err)=$server->doq($query);
    print $err if $err;
    my @wimages;
    while (my $row = $sth->fetchrow_hashref){
      #print Dumper($row);
      my $wlok = Lok->new( $row->{'about'} );
      #print "<pre>" .Dumper($wlok);
      push @wimages, $wlok->{'row'};
    } 

    $_->{'images'} = \@wimages;
  }
  $tmpl->param( words => \@words );
  #
  # /search images with word
  #





























































  #
  # search images with location
  #
  

  my $query="
   SELECT * FROM images as i 
   LEFT JOIN location as l on l.about = i.id
   WHERE l.locationname ~* $sq
  ";
  
 # print $query;


  my ($sth,$err)=$server->doq($query);
  print $err if $err;
  my @locations;
  while (my $row = $sth->fetchrow_hashref){
    # print Dumper($row);
    push @locations,$row;
  }



  foreach (@locations){
    #print $_;

    ($_->{'sword'}) = $_->{'word'} =~ m!.*\/(.*)$!;
    my $qword=$server->quote( $_->{'word'} );
    my $query="
     SELECT DISTINCT(about) 
     FROM rel_image_word
     WHERE word = $qword
    ";
    my ($sth,$err)=$server->doq($query);
    print $err if $err;
    my @wimages;
    while (my $row = $sth->fetchrow_hashref){
      #print Dumper($row);
      my $wlok = Lok->new( $row->{'about'} );
      #print "<pre>" .Dumper($wlok);
      push @wimages, $wlok->{'row'};
    } 

    $_->{'images'} = \@wimages;
  }
  $tmpl->param( locations => \@locations );
  #
  # /search images with word
  #



  if (1){
    #
    # search images with comment
    #
    
    my $query = "SELECT * FROM images WHERE comment ~* $sq";
    my ($sth,$err)=$server->doq($query);
    print $err if $err;
    my @timages;
    while (my $row = $sth->fetchrow_hashref){
      my $tlok = Lok->newfromid($row->{'serial'} );
      # print Dumper($tlok);
      push @timages, $tlok->{'row'};
    }
    $tmpl->param(timages => \@timages);
  }










#20040911
unless ($cgitmpl =~ /inner/){
if (@persons >1 ){
	print "TODO: multple person gevonden.";
	exit;
}
}


  $tmpl->param( 
	       search   => $search,
	       personq  => \@persons,
	      );

  
} # /if zoek


if ( $q->param('imageid') ){
  my $lok=Lok->new($q->param('imageid') );
  foreach my $var (keys %{ $lok->{'row'} }){
    $tmpl->param($var => $lok->{'row'}->{$var} ,)
  }
  my $depicts=Person->new( { lok => $lok } );
  if ($depicts){
    $tmpl->param( 'depicts' => $depicts,);

    print Dumper($depicts) if $debug;

  }
  print Dumper($lok) if $debug;
}




# all imageperson
#my $ps=new Person( { all => 1, } );

#if ($action eq 'all'){
# foreach  ( @{$ps} ){
#  my $id=$_->{'id'};

#  my $mbox=$_->{'mbox'};
#  unless ($mbox =~ m!^mailto:!){
#      $mbox = "mailto:$mbox";
#  }
#  my $sha1=sha1_hex( $mbox );
#  $_->{'sha1'}=$sha1;
#  my $qid=$server->quote($id);
#  my $query = "
#SELECT * FROM images as i, rel_image_person as ip
#WHERE i.id=ip.imageid
#AND ip.personid=$qid
# ";
#  my ($sth,$err)=$server->doq($query);
#  die $err if $err;
#  my @is;
#  while (my $row=$sth->fetchrow_hashref){
#    push @is,$row;
#  }
#  $_->{'images'}=\@is;
#
#}


#}



#my $dump =  Dumper($ps);

my $overloop;
foreach  my $i ( qw(a b c d e f g h i j k l m n o p q r s t u v w x y z )){
  my $row;
  $row->{'text'} = $i;
 push @{$overloop}, $row;
}


my $voet=voet2('person');



$tmpl->param(
 voet => $voet,
# dump   => $dump ,
# person => $ps ,
# persons => $ps ,
 msg     => $msg,	     
overloop => $overloop,
           );


my $end=[gettimeofday];
my $elapsed = tv_interval ( $start, $end );
$tmpl->param(
             elapsed => $elapsed,
);



my $output = $tmpl->output;

if( $cgitmpl =~ m!foaf! ){
 # 20031003 parse
 $output =~ s!\&eacute;!e!;
}


print $output;
# /all imageperson







