#!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_structmap = [];


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 structmaps, choose structmap/physical
    my @structmaps = @{$goobi_doc->{'mets:mets'}->[0]->{'mets:structMap'}};
    my @structmap = ();
    foreach my $s_map (@structmaps)
    {
    	@structmap = @{$s_map->{'mets:div'}->[0]->{'mets:div'}} if ($s_map->{'TYPE'} eq 'PHYSICAL');
    }
    
    
    foreach my $page (@structmap)
    {
    	my $newpage = {};
    	   $newpage->{'structId'} = $page->{'ID'};
    	   $newpage->{'order'}    = $page->{'ORDER'};
    	   $newpage->{'label'}    = $page->{'ORDERLABEL'};
    	   push @{$shortened_structmap},$newpage;
    }
    
    # store to disc
    open FILE,'>'.$TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'pages'};
    print FILE Dumper $shortened_structmap;
    close FILE;
    
    message("$msg_ok Paginierung zwischengespeichert.");
    
    # clear large data structures
    $goobi_doc = undef;
    $xs = undef;
}

#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;
}
