package Atok_plugin;

use strict;
use utf8;
#use Cwd;
#use Encode;
use DBI;
#use Data::Dumper;
#use MeCab;

#my $CD = Cwd::getcwd() . "/";
#my $temp_file = "temp";
my $database_file = "TANSI_v110.sqlite.db";

sub run_process
{
  my( $a_request_data ) = @_;

  my %result_data;

  my @candidate_array;
  my @yure_candidates = [];
  my @word_candidates;
    
  my $for_searchengines;
  my $for_regex;
  
  my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file","","");

  my $sql_ref = $dbh -> selectall_arrayref('SELECT WORD, HINSI1, CANDIDATES, HINSI2 FROM TANSI WHERE WORD LIKE "' . $a_request_data->{ 'composition_string' } . '";');


  if($sql_ref){
    for(my $i = 0 ; $i < @$sql_ref ; $i++){
      @yure_candidates = split(/\//, @$sql_ref[$i]->[2]);
      $for_searchengines = '"' . join('" OR "',@yure_candidates) . '"';
      $for_regex = join(' | ',@yure_candidates);
      push(@word_candidates, @yure_candidates);
      push( @candidate_array , {'hyoki' => $for_searchengines,
                                'alternative' => @$sql_ref[$i]->[1] . @$sql_ref[$i]->[3],
                                'alternative_type' => 'definite_string'} );
      push( @candidate_array , {'hyoki' => $for_regex,
                                'alternative' => @$sql_ref[$i]->[1] . @$sql_ref[$i]->[3],
                                'alternative_type' => 'definite_string'} );
      push( @candidate_array , {'hyoki' => '(' . $for_regex . ')',
                                'alternative' => @$sql_ref[$i]->[1] . @$sql_ref[$i]->[3],
                                'alternative_type' => 'definite_string'} );
    }
    foreach my $j (@word_candidates){
        push( @candidate_array , {'hyoki' => $j } );
    }
  }

  if($@){
    $dbh -> disconnect;
    die "Error: $@";
  }
  
  #MeCab
  ###################################################################################
  #my $return_MORPHANA = system('mecab --node-format="%m\t%f[0]\t"' . $filepath);
  #my $return_MORPHANA = `mecab --node-format="%m\t%f[0]\t" $filepath`;
  #exec('mecab ' . $filepath . "> temp2");
  ###################################################################################

  $result_data{ 'candidate' } = \@candidate_array;

  return( %result_data );
}

1;
