#!/usr/bin/perl -w
#
#   This program is free software; you can redistribute it and/or modify  
#   it under the terms of the GNU General Public License as published by  
#   the Free Software Foundation; either version 3 of the License, or     
#   (at your option) any later version.                                   
#                                                                         

$| = 1;

#use strict;
#use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Config::Std;

our $cgi = new CGI;
print $cgi->header();

our $dir = './';

my $temp_genus       = $cgi->param('genus');
my $temp_noun_or_not = $cgi->param('noun_or_not');
my $temp_word_type   = $cgi->param('word_type');     
my $use_speech       = $cgi->param('speech');

my $question = $cgi->param('ask');

my $log  = $cgi->param('log');
my $lang = $cgi->param('lang') || $cgi->param('language');

sub LANGUAGE {
	return $lang || 'de';
}



sub footer {
	return if $show_simple;
	
	open my $template, "<", "footer-extra.template.html";
	print join '', <$template>;
	close $template;
}


my $submit_and_get_answer = (LANGUAGE() eq 'de') ? 'Absenden und vorherigen Satz beantworten'
                                        : 'submit and get answer';
 
my $please_enter = (LANGUAGE() eq 'de') ? 'Bitte Satz eingeben:'
                                        : 'Please enter a sentence:';
                                        
my $button_answer = (LANGUAGE() eq 'de') ? 'Antworten!'
                                         : 'Get answer!';

my $button_abort = (LANGUAGE() eq 'de') ? 'Beantwortung abbrechen und zur&uuml;ck zur Frageeingabe!'
                                         : 'Abort answering!';

my $speech_on    = (LANGUAGE() eq 'de') ? 'Sprachausgabe ein!'
                                        : 'Text to speech on' ;

my $speech_off   = (LANGUAGE() eq 'de') ? 'Sprachausgabe aus!'
                                        : 'Text to speech off';


sub impl_get_genus {
	my ( $CLIENT_ref, $word ) = @_;
	my $CLIENT = $$CLIENT_ref;

	if ($temp_genus) {
		my $temp = $temp_genus;
		$temp_genus = undef;
		return $temp;
	}

	print << "	EOT";
	
	--></div>
	
	<p>
	EOT
	if ( LANGUAGE() eq 'de' ) {
		print << "		EOT";
	Welches grammatische Geschlecht (der, die, das) hat das Wort "$word"?
		EOT
	}
	else {
		print << "		EOT";
	Which genus is "$word"?
		EOT
	}
	print << "	EOT";
	</p>
	
	<form method="post">
	<select name='genus' size='5'>
	EOT
	if ( LANGUAGE() eq 'de' ) {
		print << "		EOT";
 		<option value='1'>m&auml;nnlich (der, ein)</option>
 		<option value='2'>weiblich (die, eine)</option>
 		<option value='3'>s&auml;chlich (das, ein)</option>
		EOT
	}
	else {
		print << "		EOT";
 		<option value='1'>male</option>
 		<option value='2'>female</option>
 		<option value='3'>thing</option>
		EOT
	}
	print << "	EOT";
 	</select>	<br/>	<br/>
	<input type="hidden" name="lang" value="$lang" />
	<input type="hidden" name="speech" value="$use_speech" />
	<input type="hidden" name="log" value="$log" />
 	<input type="hidden" name="ask" value="$question" />
 	<button name="ok" type='submit'>$submit_and_get_answer</button>
	EOT
	print '<input type="hidden" name="noun_or_not" value="' . ($cgi->param('noun_or_not')) . '" />';
	
	print << "	EOT";
	</form>
 	<br />
	<form method="post">
	<input type="hidden" name="log" value="$log" /><br />
	EOT
print '<input type="hidden" name="lang" value="' . LANGUAGE() . '" />';
print << "	EOT";
	</select>
	<button name="ok" type='submit'>$button_abort</button>
	</form>
	EOT
	
	print footer();

	exit 0;
}

sub impl_get_noun_or_not {
	my ( $CLIENT_ref, $word ) = @_;
	my $CLIENT = $$CLIENT_ref;

	if ($temp_noun_or_not) {
		my $temp = $temp_noun_or_not;
		$temp_noun_or_not = undef;
		return $temp;
	}

	print << "	EOT";

	--></div>
	
	<p>
	EOT
	if ( LANGUAGE() eq 'de' ) {
		print << "		EOT";
	Ist das Wort "$word" als Nomen gemeint ?
		EOT
	}
	else {
		print << "		EOT";
	Is "$word" meant as a noun?
		EOT
	}
	print << "	EOT";
	</p>
	
	<form method="post">
	<select name='noun_or_not' size='5'>
	EOT
	if ( LANGUAGE() eq 'de' ) {
		print << "		EOT";
 		<option value='1'>Nomen oder Name, z.B. Computer, Haus, Auto, oder ein beliebiger Name</option>
 		<option value='2'>kein Nomen und kein Name</option>
		EOT
	}
	else {
		print << "		EOT";
 		<option value='1'>it is a noun</option>
 		<option value='2'>it is no noun</option>
		EOT
	}
	print << "	EOT";
 	</select>	<br/>	<br/>
	<input type="hidden" name="lang" value="$lang" />
	<input type="hidden" name="speech" value="$use_speech" />
	<input type="hidden" name="log" value="$log" />
 	<input type="hidden" name="ask" value="$question" />
 	<button name="ok" type='submit'>$submit_and_get_answer</button>
	</form>
 	<br />
	<form method="post">
	<input type="hidden" name="log" value="$log" /><br />
	EOT
print '<input type="hidden" name="lang" value="' . LANGUAGE() . '" />';
print << "	EOT";
	</select>
	<button name="ok" type='submit'>$button_abort</button>
	</form>
	EOT

	print footer();

	exit 0;
}

sub impl_get_word_type {
	my ( $CLIENT_ref, $word ) = @_;
	my $CLIENT = $$CLIENT_ref;

	if ($temp_word_type) {
		my $temp = $temp_word_type;
		$temp_word_type = undef;
		return $temp;
	}

	print << "	EOT";
	
	--></div>

	<p>
	EOT
	if ( LANGUAGE() eq 'de' ) {
		print << "		EOT";
	Welche Wortart hat das Wort "$word"?
		EOT
	}
	else {
		print << "		EOT";
	Which word type is "$word"?
		EOT
	}
	print << "	EOT";
	</p>
	
	<form method="post">
 	<select name='word_type' size='6'>
	EOT
	if ( LANGUAGE() eq 'de' ) {
		print << "		EOT";
 		<option value='2'>Nomen oder Name oder Pronomen (Beispiel: Computer, Haus, Auto, oder ein beliebiger Name)</option>
 		<option value='1'>Verb (Beispiel: machen, tun, laufen, arbeiten)</option>
 		<option value='3'>Adjektiv oder Adverb (Beispiel: schnell, langsam, gut, schlecht, unm&ouml;glich)</option>
 		<option value='5'>Fragewort oder Konjunktion (Beispiel: wer, wie, was, warum, wann, wo oder weil, wenn, falls, dass, ...)</option>
 		<option value='6'>Pr&auml;position (Beispiel: auf, in, an, ab, unter, neben, um, von, am, gegen, ...)</option>
 		<option value='7'>Interjektion / Ausruf (Beispiel: ja, nein, doch, Hallo, ...)</option>
		EOT
	}
	else {
		print << "		EOT";
 		<option value='2'>noun or name or pronoun</option>
 		<option value='1'>verb</option>
 		<option value='3'>adjective or adverb</option>
 		<option value='5'>question word or conjunction</option>
 		<option value='6'>preposition</option>
 		<option value='7'>interjection</option>
		EOT
	}
	print << "	EOT";
 	</select><br/><br/>
	<input type="hidden" name="lang" value="$lang" />
	<input type="hidden" name="speech" value="$use_speech" />
	<input type="hidden" name="log" value="$log" />
 	<input type="hidden" name="ask" value="$question" />
 	<button name="ok" type='submit'>$submit_and_get_answer</button>
 	<br />
	<form method="post">
	<input type="hidden" name="log" value="$log" /><br />
	EOT
print '<input type="hidden" name="lang" value="' . LANGUAGE() . '" />';
print << "	EOT";
	</select>
	<button name="ok" type='submit'>$button_abort</button>
	</form>

	EOT
	print '<input type="hidden" name="noun_or_not" value="' . ($cgi->param('noun_or_not')) . '" />';
	
	print << "	EOT";

	</form>		 		
	EOT

	print footer();

	exit 0;
}

if (!$show_simple) {
	open my $template, "<", "header-extra.template.html";
	print join '', <$template>;
	close $template;
}
if ( LANGUAGE() eq 'de' && !$show_simple ) {
	print << "	EOT";
<p>Dies ist die Online Version von <i>JEliza Perl</i>. Hier k&ouml;nnen Sie die k&uuml;nstliche Open-Source-Intelligenz
in ihrem Webbrowser ausprobieren.</p>

	EOT
}
elsif ( !$show_simple ) {
	print << "	EOT";
<p>This is the online version of our artificial intelligence <i>JEliza Perl</i>.</p>
	EOT
}
print << "EOT";

EOT

require 'jeliza-engine.pl';
$in_cgi_mode = 1;

#print "LANG: ", $lang;

#print $cgi->param('log');

my $statement = << "EOT";
<p style="color: black !important; font-size: 10pt !important; line-height: 28px; margin: 15px !important; background-color: #ffca9b !important; padding: 10px !important;">
	Wir bitten um seri&ouml;se Gespr&auml;che mit JEliza; <br />
	JEliza ist ein ernst gemeintes Projekt zur Entwicklung eines Gespr&auml;chssimulators. <br />
	Daher bittet das JEliza Team ausdr&uuml;cklich darum, an Beleidigungen und vulg&auml;ren Ausdr&uuml;cken zu sparen.
</p>
EOT

print $statement if !$cgi->param('ask') && !$show_simple;


if ( $cgi->param('check_is_true') ) {
	load_word_types();
	load_database_file( $dir . "/lang_" . LANGUAGE() . "/facts.pro" );

	do_check_is_true_on_facts($cgi->param('check_is_true'));
}

if ( $cgi->param('ask') ) {
	my $display_str = '';

	open my $CLIENT, ">>", "to-server.log";

	print "<div style='display:none;'><!--";

	load_word_types();
	load_database_file( get_database_files() );

	my $dialog = ask( \$CLIENT, $cgi->param('ask'), \$display_str );
	$log .= $dialog;

	print "--></div>\n\n";
	
	$log =~ s/[:]+/:/igm;
	
	$log =~ s/\n//gm;
	
	chomp $log;
	
	my @log_lines = split /[<]br/, $log;

	print $statement if (@log_lines <= 3 || !$log) && !$show_simple;

	if ( $show_simple ) {
		my $config_file  = 'talk-protocol.cfg';

		if ( not( -f $config_file ) ) {
			open my $handle, ">", $config_file;
			close $handle;
		}

		my %config = ();
		read_config $config_file => %config;
		print $config{ 'talk-protocol' }{ $ENV{ 'REMOTE_ADDR' } };
		$config{ 'talk-protocol' }{ $ENV{ 'REMOTE_ADDR' } } .= $log;
		write_config %config, 'talk-protocol.cfg';
	}
	
	my $log_to_display = $log;
	$log_to_display =~ s/[;]+[-]*[)]+/<img src="wink.png" \/>/igm;
	$log_to_display =~ s/[:]+[-]*[)]+/<img src="grin.png" \/>/igm;

	print << "	EOT" if !$show_simple;
<div id="talklog" style="color: black !important; font-size: 10pt !important; line-height: 28px; margin: 15px !important; background-color: #afcde2 !important; padding: 10px !important; height: 170px !important; scroll: auto !important; overflow: auto !important;">

	EOT
	
	print $log_to_display;

	print << "	EOT" if !$show_simple;
</div>

<script type="text/javascript">
var objDiv = document.getElementById("talklog");
objDiv.scrollTop = objDiv.scrollHeight;
</script>
	EOT

	$log = (split /[<]iframe/, $log)[0];
	open my $dialog_file, ">>", 'dialog.txt';
	chomp $dialog;
	$dialog =~ s/[<]br[>]/\n/igm; 
	chomp $dialog;
	$dialog =~ s/[<](.*?)[>]//igm;
	$dialog =~ s/\s*$//igm;
	$dialog =~ s/^\s*//igm;
	my $time = scalar localtime;
	my $sentences = '';
	foreach my $line (split /\n/, $dialog) {
		chomp $line;
		
		print $dialog_file $time . "\t" . $ENV{ 'REMOTE_ADDR' } . "\t" . $line . "\n";
		if ( $line =~ /^JEliza[:]/i ) {
			$line =~ s/[:]+//;
			$line =~ s/^jeliza//igm;
			$sentences .= ' ' . $line;
		}
	}
	close $dialog_file;

	print << "	EOT" if $use_speech;
	<embed src="http://tobias-schulz.info/jeliza/online/now.au.pl?text=$sentences" style="float: right; width: 0; height: 0; border: none;"s></embed>
<!--	<iframe src="" style="width: 0; height: 0; border: none;"></iframe>-->
	EOT
	# http://tobias-schulz.info/jeliza/online/now.au
}
else {
	if ( $show_simple ) {
		my $config_file  = 'talk-protocol.cfg';

		if ( not( -f $config_file ) ) {
			open my $handle, ">", $config_file;
			close $handle;
		}

		my %config = ();
		read_config $config_file => %config;
		print $config{ 'talk-protocol' }{ $ENV{ 'REMOTE_ADDR' } };
	}
	else {
		print $log;
	}
}

print << "EOT" if !$show_simple;
	<br />

	<form method="post">
	<table style="border: none;">
	<tr>
	<td style="padding-right: 20px;">
		$please_enter
	</td>
	<td colspan="2">
		<input type="text" name="ask" id="ask" value="" size="50" />
		<input type="hidden" name="log" value="$log" /><br />
	</td>
	</tr>
	<tr>
	<td>&nbsp;</td>
	<td style="width: 250px !important; padding-top: 10px !important;">
	<select name="speech">
EOT
print '	<option value="1" ' . ($use_speech ? 'selected="selected"' : '') . ">  $speech_on  </option>"  if !$show_simple;
print '	<option value="0" ' . (!$use_speech ? 'selected="selected"' : '') . ">  $speech_off  </option>"  if !$show_simple;
print << "EOT" if !$show_simple;
	</select>&nbsp;&nbsp;&nbsp;&nbsp;
	<select name="lang">
EOT
print '	<option value="en" ' . (LANGUAGE() eq 'en' ? 'selected="selected"' : '') . '>  EN  </option>'  if !$show_simple;
print '	<option value="de" ' . (LANGUAGE() ne 'en' ? 'selected="selected"' : '') . '>  DE  </option>'  if !$show_simple;
print << "EOT" if !$show_simple;
	</select>
	</td>
	<td style="padding-top: 10px !important;">
	<button name="ok" type='submit'>$button_answer</button>
	</td>
	</tr>
	<tr>
	<td colspan="2">
	<a href="jeliza-log.pl">Das gesamte Gespr&auml;chsprotokoll der letzten Tage</a>
	</td>
	</tr>
	</table>
	</form>
	
	
	<script type="text/javascript">
		document.getElementById('ask').focus();
	</script>

EOT

if ($show_simple) {
	print "<iframe src='http://developer.jeliza.org/online/jeliza-cgi.pl' style='border: none; width: 0px; height: 0px;'></iframe";
}

print footer();
exit(0);


1;
