#!/usr/bin/perl -w
use strict;

use DBI;
use Serengeti::Param;
use Serengeti::Session;
use Serengeti::Write;

$| = 2;

$main::VERSION     = '0.8.15';
$main::HTPATH      = '';
$main::DATE        = '2008-12-16';
$main::AUTHOR      = 'Nils Diewald';
$main::TITLE       = 'Serengeti Annotator';
$main::SUBTITLE    = 'Semantic Relations Annotation Tool';
$main::DESCRIPTION = 'The Serengeti Annotator is a web based client-server-application '.
                     'used for annotating semantic relations in text documents.';
$main::SESSION_COOKIENAME = 'Serengeti';
$main::SESSION_IDLENGTH = 16;
$main::SESSION_EXPIRE = '+5d';

####

my $DBUSER = 'ndiewald';
my $DBNAME = 'sgf';
my $DBPASS = 'uMzvsePe';
my $TEMPDIR = 'temp/';

my $cgi = Serengeti::Param->new('tempDir' => $TEMPDIR,'max' => 50000);

my $dbh = DBI->connect(
		       "DBI:mysql:host=localhost;database=".$DBNAME,
		       $DBUSER,
		       $DBPASS,
		       {PrintError => 0, RaiseError => 1}
		       );

$dbh->trace(1,'dbi.log');

my $s = Serengeti::Session->new(
			     'DB' => $dbh,
			     'base_pref' => 'sgf',
			     'cgi' => $cgi
			     );



#goto GUISTART if !$s;

# Parameter gegenchecken evtl.
my $action = $s->setAction(lc($s->getParam('action'))); # $s->setAction() und getAction vielleicht überflüssig.
my $frame  = lc($s->getParam('frame'));

if ($s->loggedIn()) {
    if ($frame eq 'ajax') {
	if ($s->getParam('file') && ($action ne 'group')) {
	    if (!$s->newDocument($s->getParam('file'))) {
# Error: Datei kann nicht geladen werden!
		print "Content-Type:text/plain\n\nNo document.\n";
	    };
	};
	
	my $ajax = $s->newAjax();
	
	if ($action eq 'group') {
	    if ($s->newGroup($s->getParam('group'))) {
		$s->getGroup()->getDocumentsAjax();
	    } else {
# Error: User ist nicht Mitglied der Gruppe!
	    };
	} elsif ($action eq 'load') {
	    if ($s->newDocument($s->getParam('file'))) {
# Gibt es keine AbstractAnnotation? Dann neue Anlegen.
# Gibt es eine AbstractAnnotation? Diese laden.
# Gibt es mehrere AbstractAnnotations? Liste anzeigen.
		$s->getDocument()->loadDocumentAjax();
	    } else {
# Error: Datei kann nicht geladen werden!
	    };
	} elsif ($action eq 'logout') {
	    if ($s->logout()) {
		$s->logoutAjax('true');
	    } else {
		$s->logoutAjax('false');
	    };
	} elsif ($action eq 'save') {

# Möglichkeiten:
# - Benutzer speichert in seiner einzigen Annotation ab
# - Benutzer speichert in einer weiteren Annotation ab
# - Benutzer speichert fremde Annotation ab - in Logs
	    $s->getDocument()->getAnnotation($s->getUser())->save();

#	    open (X, '>o.txt');
#	    print X $s->getParam('semrel');
#	    close(X);

#	    print "Content-Type: text/plain\n\n";
## Das geht jetzt an abstractAnnotation
#	    if ($s->getAnnotation($s->getUser())->save($s->getParam('semrel'))) {
#		print "Okay.";
#	    } else {
#		print "Nicht okay.";
#	    };
	} elsif ($action eq 'commit') {
	    $s->errorAjax('Currently not stable.');
	} else {
	    $s->errorAjax('Unknown command.');
# Error: unbekannter Befehl	    
	};
    } elsif ($frame eq 'text') {
	if ($s->getDocument()->getID() || $s->getParam('file') && $s->getDocument()->getID() != $s->getParam('file')) {
	    $s->newDocument($s->getParam('file')); # Hier testen, ob das Dokument zum Korpus gehört.
	};
	if ($s->getDocument()) {
	    $s->getDocument()->print();
	} else {
	    print "Content-Type:text/plain\n\nNo document.\n";
	};
    } elsif ($frame eq 'relations') {
	if ($s->getParam('file')) {
	    if (!$s->newDocument($s->getParam('file'))) {
# Error: Datei kann nicht geladen werden!
		print "Content-Type:text/plain\n\nNo document.\n";
	    };
	};

	if ($s->getAnnotation($s->getUser())) {
	    $s->getAnnotation($s->getUser())->print();
	} else {
# Ungeeignet, da kein Ajax-Aufruf!
	    $s->errorAjax('Cannot load annotation!');
	};
    } elsif ($frame eq 'new') {
	if ($action eq 'export') {
	    my $type = $s->getParam('type');
	    my $log = $s->getParam('log');
	    if ($s->getDocument()) {
		my $cdw = $s->getDocument();
		my $filename = 'export-'.$cdw->getXMLID().'-'.$s->getUser()->getHandle().'.xml';
		print "Content-Type: application/octet-stream\n";
		my $export;
		if ($type eq 'xml') {
		    print 'Content-Disposition: attachment; filename='.$filename."\n\n"; #$filename
		    $export = Write::STDOUT->new();
		} elsif ($type eq 'gz') {
		    print 'Content-Disposition: attachment; filename='.$filename.".gz\n\n"; #$filename
		    $export = Write::GZip->new('file' => '-');
		} else {
		    print "Content-Type: text/plain\n\nUnknown filetype.\n";
		    exit(0);
		};
		$cdw->export(
			     'base_pref' => 'sgf',
			     'out' => $export,
			     'user' => $s->getUser(),
			     'log' => $log
			     );
		$export->close();
		exit(0);
	    } else {
		print "Content-Type: text/plain\n\nThere is no document to export!";
	    };
	} else {
	    print "Content-Type: text/plain\n\nUnknown option!";
	};
    } else {
	goto GUISTART;
    };
} elsif ($action eq 'login') {
    $s = Serengeti::Session->new(
				 'DB' => $dbh,
				 'base_pref' => 'sgf',
				 'login' => $cgi->get('login'),
				 'pwd' => $cgi->get('password'),
				 'action' => 'setCookie',
				 'cgi' => $cgi,
				 );
    if ($s->loggedIn()) {
	$s->getUser()->getGroupsAjax();
    } else {
	$s->errorAjax('Login not successful!');
    };
} else {
GUISTART:
    if ($action eq 'intro') {
	my $intro = $s->newIntro();
	$intro->print();
    } elsif ($action eq 'loaddoc') {
	my ($textString, $relString) = (undef,undef);


	if ($s->loggedIn()) {
	    if ($s->getParam('group')) {
		if ($s->newGroup($s->getParam('group'))) {
		    if ($s->getParam('file')) {
			if ($s->newDocument($s->getParam('file'))) {
			    if ($s->getDocument() && $s->getDocument()->getID()) {
				$textString = '?frame=text&sid='.$s->getID().'&action=text&file='.$s->getDocument()->getID();
				$relString = '?frame=relations&sid='.$s->getID().'&action=relations&file='.$s->getDocument()->getID();
			    };
			};
		    };
		};
	    };
	};

	my $document = $s->newGui();
	$document->start();
	$document->topLine();
	$document->textFrame($textString);
	$document->footLine($relString);
	$document->end();
    } else {
	my $document = $s->newGui();
	$document->start();
	$document->topLine();
	$document->textFrame();
	$document->footLine();
	$document->end();
    };
};

$dbh->disconnect();
