#! /usr/bin/perl -w

use strict;
#use lib ".";
use MRML::Server::Base;
use MRML::Server::CLIAdapter::Visitor;
use Getopt::Long;

my $VERSION="0.01";

package MRML::Server::CLIAdapter;
require Exporter;
use strict;
use English;
use IO::File;
use vars qw(@ISA @EXPORT_OK $URL_POSTFIX $RELEVANCE_LEVEL $self $LOCAL_URL_PREFIX $TMP_FILE);

@ISA= qw(Exporter);
@EXPORT_OK= qw(new
	      );
sub new(){
  my $class = shift;
  my $self = {};
  bless $self, $class;
  $self->initialize( @_ );
  return $self;
}

sub initialize(){
  my $self=shift;

  my($i,$j);
  while($i=shift){
    $j=shift;

    $self->{$i}=$j;
  }

  $self->read_config_file();
  
#   $self->{MAX_NUMBER_OF_QUERY_IMAGES}=2;
#   $self->{PROGRAM}='my_prog';
#   $self->{QUERY_ITEM}=q($URL_POSTFIX $RELEVANCE_LEVEL );
#   $self->{START}=     q($PROGRAM $QUERY my_algorithm $TMP_FILE);
#   $self->{PARSE}=     qq(\$SCORE\" image=\"\$IMAGE\");

  $self->{server}=new MRML::Server::Base(address => $self->{address},
					 port    => $self->{port});
  $self->{visitor}=new MRML::Server::CLIAdapter::Visitor(harness => $self,
							 images  => $self->{images});
}

sub serve{
  my $self=shift;
  $self->{server}->serve(VISITOR => $self->{visitor});
}

sub read_config_file(){
  my $self=shift;

  my $l_config_file_name=$self->{"config-file"} || die "no config file given";

  my $l_config_file_handle = new IO::File;
  if ($l_config_file_handle->open("< $l_config_file_name")) {
    while(<$l_config_file_handle>){
      if(m/^[a-zA-Z_0-9]/){#if this is not a comment line
	m/^([a-zA-Z_0-9]+):/;
	my $l_entry=$POSTMATCH;
	chomp $l_entry;
	print "$1 -> $l_entry\n";

	$self->{$1}=$l_entry;
      }
    }
  }else{
    die "could not open config file $l_config_file_name: $!";
  }
  
  
}

sub make_temporary_name(){
  my $self=shift;
  return $self->{"temporary-directory"}."/tmp-$PID.txt";
}


# do_query_by_images()

sub split_list( $ @ ){
  my $self=shift;

  my $in_to_be_split=shift;
  my(@in_list)=@_;
  
  my @l_result_list;

  my $i;
  my ($l_before,$l_after,@l_after_list);

  foreach $i (@in_list){
    $i=~s/\"/\\\"/g;
  }

  foreach $i (@in_list){
    ($l_before,@l_after_list)=(split($i,$in_to_be_split));

    push @l_result_list,$l_before;
    $in_to_be_split=join("",@l_after_list);
    last if $in_to_be_split eq "";
  }

  push @l_result_list,$in_to_be_split if $in_to_be_split;
  shift  @l_result_list;

  return(@l_result_list);
}

sub do_query_by_images{
  local $self=shift;#LOCAL!!!! OTHERWISE EVAL WILL BARF
  
  my (@query_images)=(@_);
  my ($QUERY,$i);
  my $l_count=0;
  foreach $i (@query_images){
    last if $l_count>=$self->{MAX_NUMBER_OF_QUERY_IMAGES_PER_CALL};
    
    local $URL_POSTFIX=$i->[0];
    $URL_POSTFIX=~s/^$self->{REMOTE_URL_PREFIX}//;
    local $RELEVANCE_LEVEL=$i->[1];
    local $LOCAL_URL_PREFIX=$self->{LOCAL_URL_PREFIX};
    print "$LOCAL_URL_PREFIX -> $URL_POSTFIX -> $RELEVANCE_LEVEL -> $self->{QUERY_ITEM}\n";

    $QUERY.=eval("\"$self->{QUERY_ITEM}\"");
    print "$QUERY\n";
    $l_count++;
  }

  local $TMP_FILE=$self->make_temporary_name();
  my $l_run_string=eval "\"$self->{COMMAND_LINE_TO_START}\"";
  print "TO BE RUN $l_run_string\n";
  system($l_run_string);

  {
    open INFILE,"$TMP_FILE" or        die "no results in file $TMP_FILE\n";
    
    my @l_results;
    my $l_parse="§$self->{PARSE}§";
    my (@l_vars,@l_expressions);
    
    while($l_parse=~m/\$([a-zA-Z0-9]*)/g){
      #print "($MATCH/$PREMATCH/$POSTMATCH)\n";
      $l_parse=$POSTMATCH;
      push @l_vars,'$self->{'.$1.'}';
      push @l_expressions,$PREMATCH;
    }
    push @l_expressions,$l_parse;
    
    print "Variables:   ",join(",",@l_vars),"\n";
    print "Expressions: ",join(",",@l_expressions),"\n";
    
    my $l_count=0;
    my @l_result_list;
    while(<INFILE>){
	print "$_";
      chomp $_;
      $_="§$_§";
      $l_count++;
      next if $l_count <= $self->{SKIP_FIRST_LINES};
      chomp $_;
      my $l_value_string= join(",",map({"\"$_\""} $self->split_list($_,@l_expressions)));
      
      print "VALUE STRING $l_value_string\n";
      
      my $l_variable_string=join(",",@l_vars);
      eval("($l_variable_string)=($l_value_string)");
      
      $self->{IMAGE}=~s/^$self->{LOCAL_URL_PREFIX}/$self->{REMOTE_URL_PREFIX}/;
      
      push @l_result_list,[$self->{IMAGE},
			   $self->{SCORE}];
    }
    return(@l_result_list);
  }
}

