###########################################################################
#
# ExpediteeExportAction.pm -- 
# Based on HTMLToExpediteeAction.pm - Used for exporting INDIVIDUAL
# Greenstone documents to Expeditee. If you want to export an entire
# collection, use HTMLToExpediteeAction.pm.
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 2009 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###########################################################################

package ExpediteeExportAction;

use strict;

use cgiactions::baseaction;

use ExpediteeFrameIO;
use JSON;

use Devel::Peek;

BEGIN {
#    unshift (@INC, "$ENV{'GSDLHOME'}/perllib/cpan/perl-5.8");
}

@ExpediteeExportAction::ISA = ('baseaction');

# c=collect and site=xxxx implicitly handled by code
# 'c' is handled by base action, site is tested for only if greenstone3.

my $action_table=
{
	    "generate-frame"     => { 'compulsory-args' => [ "fn", "json" ],
			      'optional-args'   => ['assoc'] }, 
};

sub new
{
    my $class = shift (@_);
    my ($gsdl_cgi,$iis6_mode) = @_;

    my $self = new baseaction($action_table,$gsdl_cgi,$iis6_mode);

    return bless $self, $class;
}

sub generate_frame
{
	my $self = shift @_;
	
	my $username  = $self->{'username'};
    my $collect   = $self->{'collect'};
    my $gsdl_cgi  = $self->{'gsdl_cgi'};
    my $gsdlhome  = $self->{'gsdlhome'};

	my $assocfilepath = $self->{'assoc'};
	
    my $site = $self->{'site'};
    my $collect_dir = $gsdl_cgi->get_collection_dir($site);

    my $fn = $self->{'fn'};
	
	my $json_str_unicode = $self->{'json'}; 
	
	 if (!Encode::is_utf8( $json_str_unicode )) {
         $json_str_unicode = Encode::decode_utf8( $json_str_unicode );
     }
	 
	# decode_json expects string to convert to be raw utf8
    my $json_str_utf8 = Encode::encode("utf8",$json_str_unicode);
    my $exp_frame_tree = decode_json $json_str_utf8;	
    
    my $output_dir = &util::filename_cat($collect_dir,$collect,"export");

    if (!-d $output_dir) {
	&util::mk_dir($output_dir);
    }

    my $expeditee_frame_io = new ExpediteeFrameIO($output_dir,"kgas1A");
	 $expeditee_frame_io->buildFrame($exp_frame_tree);
	
	my $last = 0;	#check if new frame is replacing/will be the last frame in the frameset.
	 
	 if($fn == -1){
		#get last frame number and add 1.
		#BUT what if a matching frame already exists for this document but we just haven't
		#created a frameID metadata for that document yet - sol'n: at this stage, just use
		#original code of reading file names
		
		my $export_dir = &util::filename_cat($collect_dir,$collect,"export");
		my $frameInf = "$export_dir\\frame.inf";
		my $getFn = "";
		my @files;
		
		opendir DIR, $output_dir or die "cannot open output directory $output_dir: $!";
		@files = readdir DIR;
		closedir DIR;
		
		my $found = 0;
		my $frameNumString;
		for my $file(@files){
			if($file =~ m/\d/){
				
				my $fullFile = "$export_dir\\$file";
				open FILE, $fullFile or die $!;
				my @lines = <FILE>;
				my $numLines = scalar (@lines);
				my $counter = 1;
				
				for my $line(@lines){
					
					if($line eq "T \@assocfilepath $assocfilepath\n"){
						$frameNumString = $fullFile;
						
						#extract frame number out of file name
						my @getFrameNumArray = split('\\\\',$frameNumString);
						@getFrameNumArray = reverse(@getFrameNumArray);
						
						$fn = $getFrameNumArray[0];
						
						$found = 1;
						
						if($counter == $numLines){
							$last = 1;
						}
					}
					
					$counter = $counter + 1;
				}
				
				close(FILE);
			}
		}
		
		unless($found){
			#try to get frame number from frame.inf.
			if(-e $frameInf){
				
				open FRAME_INF, $frameInf or die $!;
				my @lines = <FRAME_INF>;
				
				$fn = $lines[0];
				
				#get number from string
				$fn =~ s/[^0-9]//g;
				$fn = $fn + 1;
				
				$last = 1;
			}else{
				printf "$frameInf not found\n";
				$fn = 1;
				$last = 1;
			}
		}

	 }
	 
	 
	 
	 if($expeditee_frame_io->saveFrame("$fn.exp")){
		
		printf "*** $fn";
		
		if($last){
			#update last frame number
			$expeditee_frame_io->saveLastFrameNumber($fn,$collect);
		}
		
		$gsdl_cgi->generate_message("Document Exported to Expeditee $fn");
	 }else{
		$gsdl_cgi->generate_error("Failed to save frame number $fn");
	 }
	 
	 
}

1;