#!perl

use strict;
use warnings;

use CGI;
use Template;
use JSON;

use TCE::Config;
use Pica::Records;
use Pica::Record;
use Pica::Converter;

# declare variables
my $output = {};
my $response_to_browser = {
  'success' => 0
  };
my $template_output = '';
my $anchor = 'path/to/anchor'; # only temporary

# create template toolkit cbject
my $template = Template->new({'INCLUDE_PATH' => $TCE::Config::TEMPLATES_DIR, 'OUTPUT' => $template_output});

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

# get cgi parameters
my $item_id = $cgi->param('itemid') || undef;

if (-d $TCE::Config::ITEMS.$item_id)
{
  # predefine a logical stuctmap
  my $logical_structmap = [];
  
  # get page array
  my $page_array = read_dumpfile($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'pages'});
  
  # get struct tree
  my $struct_tree = read_dumpfile($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'struct'});
  
  # get max hierarchy level
  my $max_hlevel = 0;
  foreach my $item (@{$struct_tree})
  {
    $max_hlevel = $item->{'hierarchyLevel'} if ($item->{'hierarchyLevel'} > $max_hlevel);
  }
  
  # get volume data
  my $volume_recs = Pica::Records->new($TCE::Config::ITEMS.$item_id.'/'.$TCE::Config::DATA_STORAGE{'volume'});
  
  # convert volumedata to mets:dmdsec
  my $volume = $volume_recs->next_record;
  $template_output = '';
  $template->process('mets_dmdsec.tmpl',{'record' => $volume, 'hostitem' => $volume->hostitem }) || die $template->error();
  $output->{'dmdsec'} .= $template_output;
  
  # add hostitem to logical structmap
  push @{$logical_structmap},{
    'record' => $volume->hostitem,
    'id' => $volume->hostitem->id,
    'hierarchyLevel' => $max_hlevel + 2,
    'metspointer' => $anchor } if ($volume->hostitem);
  
  # add volume to logical structmap
  push @{$logical_structmap}, {
    'record' => $volume,
    'id' => $volume->id,
    'hierarchyLevel' => $max_hlevel + 1,
    'startpage' => $page_array->[1],
    'endpage' => $page_array->[$#{$page_array}]
  };
   
  # process struct tree, convert and add struct elements to logical structmap
  my $convert = Pica::Converter->new();
  foreach my $item (@{$struct_tree})
  {
    my $pica_record = Pica::Record->new();
       $pica_record->id($item->{'id'});
    my @metadata = split(/\n/,$converter->to_picaplus(join("\n",@{$item->{'metadata'}})));
    foreach my $line (@metadata)
    {
      $pica_record->add_field($line);
    } 
    # create mets:dmdSec for each struct element
    $template_output = '';
    $template->process('mets_dmdsec.tmpl',{'record' => $pica_record}) || die $template->error();
    $output->{'dmdsec'} .= $template_output;
    
    # add to logical structmap
    $item->{'record'} = $pica_record;
    push @{$logical_structmap}, $item;
  }
  
  # convert logical structmap to mets:structMap
  $template_output = '';
  $template->process('mets_structmaplogical.tmpl',{'structmap' => $logical_structmap}) || die $template->error();
  $output->{'structmap'} .= $template_output;
    
  # convert logical structmap to mets:structLink
  $template_output = '';
  $template->process('mets_structlink.tmpl',{'structmap' => $logical_structmap}) || die $template->error();
  $output->{'structlink'} .= $template_output;
  
  # output temporary xml file 
  $template_output = '';
  $template->process('mets_container.tmpl',{'parts' => $output}) || die $template->error();
  open FILE, '>'.$TCE::Config::ITEMS.$item_id.'/tmp.xml';
  print FILE $template_output;
  close FILE;
  
  # call saxon to integrate the goobi data in temp.xml
  # TODO
  
  $response_to_browser->{'success'} = 1;
  
}

print $cgi->header( -type=>"application/json" );
print to_json($response_to_browser);
exit(0);

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