#!perl

use strict;
use warnings;

use CGI;
use File::Util;
use Template;
use Data::Dumper;

use TCE::Config;
use Pica::Records;

# global variables
our @messages;
our $go = 1;
my  $data = {};


our $msg_ok = $TCE::Config::MSG_SYMBOLS{'ok'};
our $msg_fail = $TCE::Config::MSG_SYMBOLS{'fail'};
our $msg_warn = $TCE::Config::MSG_SYMBOLS{'warn'};

# create the CGI object
my $cgi = CGI->new();

#receive cgi parameter
my $item_id    = $cgi->param('itemid') || error($msg_fail.' Es wurde kein Vorgangstitel angegeben.');
my $action     = $cgi->param('action') || undef;
my $userdata   = $cgi->param('data')   || undef;

# perform updates first, if any
if (($action eq 'updateCollections') && $go)
{
	open FILE, '>'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'collections'};
	print FILE $userdata;
	close FILE;
	
	message("$msg_ok Digitale Kollektionen erfolgreich gespeichert.");
}

if (($action eq 'updateAgent') && $go)
{
	my $agentdata; 
	if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'})
	{
		$agentdata = read_file($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'});
	}
	else
	{
		$agentdata = [\%TCE::Config::DEFAULT_AGENT];
	}
	my ($role,$type,$name) = split(/##/,$userdata);
	push @{$agentdata},{'role' => $role, 'type' => $type, 'name' => $name};
	open FILE, '>'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'};
	print FILE Dumper $agentdata;
	close FILE;
	
	message("$msg_ok Agent erfolgreich hinzugefügt");
}

if (($action eq 'deleteAgent') && $go)
{
	my $agentdata; 
	if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'})
	{
		$agentdata = read_file($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'});
	}
	else
	{
		$agentdata = [\%TCE::Config::DEFAULT_AGENT];
	}
	my ($role,$type,$name) = split(/##/,$userdata);
	
	my $i = 0;
	foreach my $agent (@{$agentdata})
	{
		splice (@{$agentdata},$i,1) if (($role eq $agent->{'role'}) && ($type eq $agent->{'type'}) && ($name eq $agent->{'name'}));
		$i++;
	}
	
	open FILE, '>'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'};
	print FILE Dumper $agentdata;
	close FILE;
	
	message("$msg_ok Agent erfolgreich gelöscht");
}

if (($action eq 'updateVolumeData') && $go)
{
	if (-e $TCE::Config::ITEMS.$item_id)
	{
	# read volume record
	my $recs = Pica::Records->new($TCE::Config::ITEMS.$item_id.'/download.dwl');
	my $picarecord = $recs->next_record;
	
	# store volume metadata to disc
	open FILE,'>'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'volume'};
	print FILE $picarecord->print_record({'xml' => 1});
	print FILE "\n";
	print FILE $picarecord->hostitem->print_record({'xml' => 1});
	close FILE; 
	message("$msg_ok Metadaten f&uuml;r den Band erneut eingelesen");
	}

}

if (($action eq 'extractCollections') && $go)
{
		# use SAXON !!!
 		$| = 1;
		
		my $stylesheet=$TCE::Config::STYLESHEET_DIR.'extractcollections.xsl';
		my $metsfile = $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'collections'};
		my $sourcefile = $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'goobi'};
		my $xslt_errors = $TCE::Config::ITEMS.$item_id.'/xsltstderr';
		
		# problematic running system() from a CGI script on a Windows machine
		open FILE, ">".$TCE::Config::ITEMS.$item_id.'/runsaxon.bat';
		print FILE '@echo off';
		print FILE "\n";
		print FILE "$TCE::Config::PATH_TO_SAXON -o:$metsfile -xsl:$stylesheet -s:$sourcefile 2>$xslt_errors";
		print FILE "\n";
		close FILE;
		
		if (system($TCE::Config::ITEMS.$item_id.'/runsaxon.bat') == 0)
		{
			message("$msg_ok Die Digitale(n) Kollektion(en) wurde erfolgreich ermittelt.");
			
		}
		else
		{
			error("$msg_fail Es ist ein Fehler beim Ermitteln der Digitalen Kollektion(en) aufgetreten.");
		}	
}

# Statistik Strukturelemente
if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'stat_struct'})
{
	open FILE, '<'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'stat_struct'};
	$data->{'statistics'}->{'struct'} = <FILE>;
	close FILE;
}
else
{
	message("$msg_warn Der Vorgang ist noch nicht bearbeitet worden. Vollständige Statistiken stehen erst zur Verfügung, nachdem der Vorgang bearbeitet und gespeichert wurde");
}

# Seiten
if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'stat_pages'})
{
	open FILE, '<'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'stat_pages'};
	$data->{'statistics'}->{'pages'} = <FILE>;
	close FILE;
}


# collections einlesen
if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'collections'})
{
	open FILE, '<'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'collections'};
	while (my $collection = <FILE>)
	{
		chomp $collection;
		push @{$data->{'collections'}}, $collection;
	}
	close FILE;
}

# agents einlesen
if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'})
{
	$data->{'agents'} =  read_file($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'agents'});
}
else
{
	$data->{'agents'} = [\%TCE::Config::DEFAULT_AGENT];
}

# createdate einlesen
if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'createdate'})
{
	$data->{'createdate'} =  read_file($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'createdate'});
}

# externalId einlesen
if (-e $TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'externalId'})
{
	$data->{'externalId'} =  read_file($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'externalId'});
}

# Read the Goobi home directory
my $fu = File::Util->new();
@{$data->{'filelist'}} = $fu->list_dir($TCE::Config::GOOBI_HOME, qw/--files-only/);

# weitere parameter einlesen


#output success/error messages to browser
my $template = Template->new({'INCLUDE_PATH' => $TCE::Config::TEMPLATES_DIR});
print $cgi->header( -type=>"text/html" );
$template->process('tce_metaitem.tmpl',{'messages' => \@messages, 'itemdata' => $data, 'itemid' => $item_id }) || die $template->error();	

exit(1);

sub error
{
	my $text = shift;
	push @messages, $text;
	$go = 0;
	return undef; 

}

sub message
{
	my $text = shift;
	push @messages, $text;
	return 1;
}

sub read_file
{
  my $filename = shift;
  open FILE, '<'.$filename;
  my @lines = <FILE>;
  close FILE;
  my $object = join('',@lines);
  my $VAR1;
  eval ($object);
  return $VAR1;	
}