#!perl

use strict;
use warnings;

#use CGI::Carp qw(fatalsToBrowser);

use CGI;
use File::Copy;
use File::Util;
use Template;
use XML::Simple;
use Data::Dumper;

use TCE::Config;


# global variables
our @messages;
our $go = 1;
our $shortened_imagemap = [];


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 File::Util object
my $fu = File::Util->new();

# 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. Daher konnte kein neuer Vorgang angelegt werden.');

if ($go)
{

    #extract information from goobi file
    my $xs = XML::Simple->new(ForceArray => 1, KeepRoot => 1);
    my $goobi_doc = $xs->XMLin($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'goobi'});
    
    # extract fileGroups, choose fileGrp/default
    if ($goobi_doc->{'mets:mets'}->[0]->{'mets:fileSec'}->[0]->{'mets:fileGrp'})
    {
	    my @filegroups = @{$goobi_doc->{'mets:mets'}->[0]->{'mets:fileSec'}->[0]->{'mets:fileGrp'}};
	    my @filegroup = ();
	    foreach my $s_map (@filegroups)
	    {
	    	@filegroup = @{$s_map->{'mets:file'}} if ($s_map->{'USE'} eq 'DEFAULT');
	    }
	    
	    foreach my $page (@filegroup)
	    {
	    	push @{$shortened_imagemap},$page->{'mets:FLocat'}->[0]->{'xlink:href'};
	    }
	    unshift @{$shortened_imagemap},'http://localhost/tce/include/images/default.jpg';
	    
	    # store to disc
	    open FILE,'>'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'images'};
	    print FILE Dumper $shortened_imagemap;
	    close FILE;
	
	    # store statistics to disc
	    open FILE,'>'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'stat_pages'};
	    print FILE $#{$shortened_imagemap};
	    close FILE;
	    
	    message("$msg_ok Image URLs zwischengespeichert.");
	    
	    # clear large data structures
	    $goobi_doc = undef;
	    $xs = undef;
    }
    else
    {
    	message("$msg_warn Die eingelesene Goobi-Datei enthält keine Verweise auf Bilddateien. Möglicherweise haben Sie eine Ankerdatei eingelesen.");
    }
    
}

#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_createitem_message.tmpl',{'messages' => \@messages, 'success' => $go, '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;
}
