package disttmx;

use Data::Dumper;
use NAT;
use NAT::Lexicon;
use NAT::Dict;
use NAT::Translator::method1;

use Search::Glimpse;
use strict;

my $path = '/home/www/cgi-bin/PC/PT.10percent-EN.10percent';
our %config = (
	       'pt-en' => {
			   sLex => "$path/PT.10percent.lex",
			   tLex => "$path/EN.10percent.lex",
			   sDic => "$path/PT.10percent.bin",
			   tDic => "$path/EN.10percent.bin",
			  },
	       'en-pt' => {
			   sLex => "$path/EN.10percent.lex",
			   tLex => "$path/PT.10percent.lex",
			   sDic => "$path/EN.10percent.bin",
			   tDic => "$path/PT.10percent.bin",
			  },
	      );

our %known_languages = (
		        en => [qw/pt/],
			pt => [qw/en/],
		       );

sub lang_pair
  {
    my ($self, $l1, $l2) = @_;

    if (exists($known_languages{$l1})) {
      if (grep { $_ eq $l2 } @{$known_languages{$l1}}) {
	return 1;
      }
    }
    return 0;
}

sub equiv {
  my ($self, $l1, $l2, $string) = @_;

  my $x = Search::Glimpse->new('server'  => 'linguateca.di.uminho.pt',
			       'nr_hits' => 1);

  my @answers  = $x->search($string);

  if ($answers[0] eq "ERROR")
    { return undef }
  else {
    my $i = 0;
    @answers = map { s!^[^:]+:!!;
		     s!^\s*<[^>]+>!!;
		     s!</tu>$!!;
		     s!</tu><tu[^>]+>!#XPTO#!;
		     if ($l1 eq "pt") {
		       [ split /#XPTO#/ ]
		     } else {
		       my ($x,$y) = split /#XPTO#/;
		       [ $y, $x ]
		     }
		   } @answers;
    return align($l1,$l2,$string,@{@answers[0]});
  }
}

sub align {
  my ($l1, $l2, $query, $s,$t) = @_;
  my $key = $l1."-".$l2;
  my $data = $config{$key};
  my $self = {};
  $self->{sLex} = NAT::Lexicon::open($data->{sLex});
  $self->{tLex} = NAT::Lexicon::open($data->{tLex});
  $self->{sDict} = NAT::Dict::open($data->{sDic});
  $self->{tDict} = NAT::Dict::open($data->{tDic});

  my @search_words = @{$self->{sLex}->sentence_to_ids($query)};
  my $ssize = $#search_words + 1;

  my $source = "" ; # de momento nao e' usada. join(" ",@{$self->{sLex}->sentence_to_ids($s)});
  my $target = join(" ",@{$self->{tLex}->sentence_to_ids($t)});

  my ($x,$z) = NAT::Translator::method1::method($self,
						\@search_words,
						$ssize,
						$source,
						$target);
  return $x;
}

sub conc {
  my ($self, $l1, $l2, $string) = @_;

  my $x = Search::Glimpse->new('server'  => 'linguateca.di.uminho.pt',
			       'nr_hits' => 40);

  my @answers  = $x->search($string);
  return undef if $answers[0] eq "ERROR";

  @answers = map { s!^[^:]+:!!;
		   s!^\s*<[^>]+>!!;
		   s!</tu>$!!;
		   s!</tu><tu[^>]+>!#XPTO#!;
		   if ($l1 eq "pt") {
		      [ split /#XPTO#/ ]
                   } else {
                      my ($x,$y) = split /#XPTO#/;
                      [ $y, $x ]
                   }
		 } @answers;

  return [@answers];

}


1;
