###########################################################################
#
# TippleExportJSONPlugin.pm
#   -- A plugin for processing the JSON format exported from a Tipple server
#
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright 2023 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 TippleExportJSONPlugin;


use SplitJSONFile;

use strict;
no strict 'refs';
#use multiread;

use Encode;
use JSON;

# methods with identical signatures take precedence in the order given in the ISA list.
sub BEGIN {
    @TippleExportJSONPlugin::ISA = ('SplitJSONFile');
}



my $arguments = [
#       { 'name' => "process_exp",
# 	'desc' => "{BaseImporter.process_exp}",
# 	'type' => "regexp",
# 	'reqd' => "no",
# 	'deft' => &get_default_process_exp() },
    { 'name' => "split_exp",
      'desc' => "{SplitJSONFile.split_exp}",
      'type' => "string",
#      'deft' => "contentGroups,contentItems",
      'deft' => "contentItems",
      'reqd' => "no" },
    { 'name' => "metadata_exp",
      'desc' => "{SplitJSONFile.metadata_exp}",
      'type' => "string",
      'deft' => "WAIATA",
#      'deft' => "",
      'reqd' => "no" },    
];

# Other document-level metadata types to consider:
#
# .contentGroups:   
#    COMPOSER
#    GENRE
#    HAPU
#    OCCASION
#    TOPIC
#    WRITER
#
# .contentItems:
#   CONTENT_PAGE
#   TK_LABEL

# =>
#    'deft' => "COMPOSER,GENRE,HAPU,OCCASION,TOPIC,WRITER , WAIATA,CONTENT_PAGE,TK_LABEL",


my $options = { 'name'     => "TippleExportJSONPlugin",
		'desc'     => "{TippleExportJSONPlugin.desc}",
		'abstract' => "no",
		'inherits' => "yes",
		'args'     => $arguments };


sub new
{
    my ($class) = shift (@_);
    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
    push(@$pluginlist, $class);

    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
    push(@{$hashArgOptLists->{"OptList"}},$options);

    my $self = new SplitJSONFile($pluginlist, $inputargs, $hashArgOptLists);

    my $metadata_exp = $self->{'metadata_exp'};
    my @metadata_exps = split(/\s*,\s*/,$metadata_exp);

    $self->{'metadata_exp_lookup'} = {};
    
    foreach my $md_exp_and_opt_mapping (@metadata_exps) {
	print STDERR "**** md_ext_and_opt_mapping = $md_exp_and_opt_mapping\n";
	
	my ($md_exp,$opt_mapping) = ($md_exp_and_opt_mapping =~ m/^(.+?)(?:->(.+))?$/);
	$self->{'metadata_exp_lookup'}->{$md_exp} = { 'exists' => 1, 'gs_metadata_name' => $opt_mapping }; # note: $opt_mapping might be undef
    }

    return bless $self, $class;
}


#sub get_default_process_exp
#{
#    return q^(?i)\.json$^;
#}


####
# Example 1: Document Section of Tipple (minimal)
####
#
#        {
#             "documents": [],
#             "id": 3786,
#             "mediaItems": [],
#             "name": "Te Kooti Arikirangi Te Turuki",
#             "type": "COMPOSER"
#         },

####
# Example 2: Document Section of Tipple (audio)
####
#
#         {
#             "documents": [
#                 {
#                     "locale": {
#                         "code": "en"
#                     },
#                     "roles": [
#                         {
#                             "code": "DESCRIPTION",
#                             "type": "DESCRIPTION"
#                         }
#                     ],
#                     "sections": [
#                         {
#                             "caption": "Lyrics",
#                             "collapsed": false,
#                             "content": "Dark cloudy night, good for eeling\nHold the eeling rod at Waitangi. Waitangi Tahi.\nI prepare my kete of fern roots, when it is filled\nThen turn around, go south to the mountain Titiwa\nHave to be like a paua to climb it's steepness\nThen carry on past going south to the boundaries of Gisborne.\nThen turn and go west to Uenuku\nThis area is acknowledged by a rock, Te Karoro a Tamatea,\nThe rock where Tamatea hit and split his canoe,\nAlso in the same incident, bumped his nose and it bled\nI then jump the shores of K\u0101napanapa\nTo collect water to take to Te Pua-ki-Te-Reinga\nI then grasp my kete of belongings by the handles\nI look back with sadness and yearning to my land region\nNo one sees the sadness within me\nAs I bow and turn my head with sorrow",
#                             "type": "text"
#                         },
#                         {
#                             "caption": "Explanation",
#                             "collapsed": false,
#                             "content": "This Te Whakat\u014dhea waiata tangi sung at Waioweka, the hap\u016b of Ng\u0101ti Ira, captures the plight of it's people in a war ravaged environment. It reflects the pain and suffering our people have endured for the past 155 years.\n\nSome of the singers that can be heard are our koroua and kuia, Kaiora Tai, Himiona Kahika, Rea Rewiri and Heeni Tawhara. This recording was done at Te Rere p\u0101, 13 Tihema 1971, following the Tekau m\u0101 Rua.\n\nThe explanation given was in regards to a woman named Moa, who composed this waiata, after his lover deserted her.",
#                             "type": "text"
#                         }
#                     ]
#                 },
#                 {
#                     "locale": {
#                         "code": "en"
#                     },
#                     "roles": [
#                         {
#                             "code": "TEASER",
#                             "type": "TEASER"
#                         }
#                     ],
#                     "sections": [
#                         {
#                             "collapsed": false,
#                             "content": "A traditional chant of Ng\u0101ti Ira.  In this recording you can hear the voices of our pakeke.",
#                             "type": "text"
#                         }
#                     ]
#                 },
#                 {
#                     "locale": {
#                         "code": "mi_NZ"
#                     },
#                     "roles": [
#                         {
#                             "code": "TEASER",
#                             "type": "TEASER"
#                         }
#                     ],
#                     "sections": [
#                         {
#                             "collapsed": false,
#                             "content": "He m\u014dteatea t\u0113nei o Ng\u0101ti Ira.  Ka rongo ki te te reo waiata o r\u0101tou m\u0101",
#                             "type": "text"
#                         }
#                     ]
#                 },
#                 {
#                     "locale": {
#                         "code": "mi_NZ"
#                     },
#                     "roles": [
#                         {
#                             "code": "DESCRIPTION",
#                             "type": "DESCRIPTION"
#                         }
#                     ],
#                     "sections": [
#                         {
#                             "caption": "Kupu",
#                             "collapsed": false,
#                             "content": "T\u0113r\u0101 te p\u014d pango\nPuritia mai te tautara ki Waitangi r\u0101 e\nKo te rite i taku tarai i k\u012ba mai nei\nTahuri ka Titiwa tonu\nTitiwa mai ana a roto he paua piri ki te toka\nKia m\u0101m\u0101 tonu atu ko te t\u014dnga atu o te r\u0101\nKi \u014dna papaihoretanga ki a Uenuku\nKo te toka i a Parirau ko te Karoro a Tamatea\nMe he ako ia nei te waka nei ka pakaru ki taku tinana\nPenei i reia e au ki te ihu o te tio hakia e\nPeke ana au ki te tai ng\u0101 riu o K\u0101napanapa\nHei kawe i ng\u0101 wai e ahau ki Te Pua-ki-Te-Reinga\nKia hopu nei \u014d akap\u016b te taunga atu ki t\u0101whiti e\nTe pae ki taiao mai\nKo wai ka kite i au e?\nKo te whakam\u0101 hoki rawa t\u0113nei ka t\u014dtope i taku rae e i...",
#                             "type": "text"
#                         },
#                         {
#                             "caption": "Whakam\u0101rama",
#                             "collapsed": false,
#                             "content": "He waiata aroha t\u0113nei. He k\u014drero e p\u0101 ana ki \u0113tahi whenua o Ng\u0101ti Ira, o Waioweka. Ka rite an\u014d te k\u014drero nei m\u014d te rohe whenua o Ng\u0101ti Ira o Waioweka \"Waitangi Tahi ki te raki, Titiwa ki te rawhiti, Waitangi Rua ki te Tonga, Matiti ki te hauauru. He k\u014drero tuku iho m\u014d te rohe whenua o Ng\u0101ti Ira. He k\u014drero an\u014d e whakaatu mai i te mamae me te p\u0101katokato o te iwi nei, o Te Whakat\u014dhea.\n\nKo \u0113tahi kaiwaiata e rangona nei, ko Kaiora Tai, Himiona Kahika, ko Rea Rewiri, ko Heeni Tawhara me ng\u0101 toenga o ng\u0101 tamariki a Iharaira. I te 13 TIhema 1971, katahi ka mutu te Tekau m\u0101 Rua ki runga o Te Rere p\u0101, n\u0101 ki reira ka hopungia e Mervyn McLean i te waiata nei.\nKi t\u0101 te whakam\u0101rama o ng\u0101 kaiwaiata, n\u0101 t\u0113tahi wahine, ko Moa t\u014dna ingoa, i whakar\u0113rea atu i a ia e tana whai\u0101ip\u014d.",
#                             "type": "text"
#                         }
#                     ]
#                 }
#             ],
#             "id": 836,
#             "mediaItems": [
#                 {
#                     "displayOrder": 1000,
#                     "file": {
#                         "contentType": "audio/mp3",
#                         "size": 1838394,
#                         "sourceUri": "https://koicarp.cms.waikato.ac.nz/td/v1/public/files/d9c6c7de-4591-41d3-b079-191f8ce37bd0.mp3",
#                         "uri": "~/assets/audio/content/d9c6c7de_4591_41d3_b079_191f8ce37bd0.mp3"
#                     },
#                     "id": 9760,
#                     "roles": [
#                         {
#                             "code": "READ_ALOUD",
#                             "type": "READ_ALOUD"
#                         }
#                     ]
#                 }
#             ],
#             "name": "T\u0113r\u0101 te p\u014d pango",
#             "type": "WAIATA"
#         },



# do plugin specific processing of doc_obj
sub process {

    my $self = shift (@_);
    my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;

    my $outhandle = $self->{'outhandle'};
    my $verbosity = $self->{'verbosity'};

    my $metadata_exp = $self->{'metadata_exp'};
    my $metadata_exp_lookup = $self->{'metadata_exp_lookup'};
    	
    my $cursection = $doc_obj->get_top_section();


    my $json_rec = JSON::from_json($$textref); # expects unicode string

    my $json_pretty = JSON->new()->pretty();
    my $json_unicode_str = $json_pretty->encode($json_rec); # expects unicode string
    
    if ($verbosity>=4) {

	my $json_utf8_printable_str = Encode::encode("utf8",$json_unicode_str);
	print $outhandle "TippleExportJSONPlugin.pm::processing segment\n";
	print $outhandle "===========\n";
	print $outhandle "$json_utf8_printable_str\n";
	print $outhandle "===========\n";
	
    }

    # tipple name -> Title
    # tipple type (e.g. genre, writer, composer ) -> Type

    my $tipple_name = $json_rec->{'name'};
    my $tipple_type = $json_rec->{'type'};

    my $tipple_type_formatted = ucfirst(lc($tipple_type));
    
    my $is_metadata_name_match = 0;
    my $gs_metadata_name;
	
    if ($metadata_exp eq "") {
	$is_metadata_name_match = 1;
	$gs_metadata_name= $tipple_type_formatted;
    }
    elsif (defined $metadata_exp_lookup->{$tipple_type}) {
	$is_metadata_name_match = 1;
	if (defined $metadata_exp_lookup->{$tipple_type}->{'gs_metadata_name'}) {
	    $gs_metadata_name = $metadata_exp_lookup->{$tipple_type}->{'gs_metadata_name'};
	}
	else {
	    $gs_metadata_name= $tipple_type_formatted;
	}
    }
	
    if ($is_metadata_name_match) {
	
	$doc_obj->add_utf8_metadata($cursection, "Title",$tipple_name);
	$doc_obj->add_utf8_metadata($cursection, "Type", $tipple_type_formatted);
	
	# .documents
	#	.locale
	#     .code
	#	.roles
	#     .type 
	#	.sections
	#     .caption + .content
	#
    
	my $tipple_documents = $json_rec->{'documents'};
	foreach my $tipple_document (@$tipple_documents) {

	    # 'documents' in tipple corresponds to 'section of document' in greenstone
	    
	    my $tipple_locale   = $tipple_document->{'locale'};
	    my $tipple_roles    = $tipple_document->{'roles'};
	    my $tipple_sections = $tipple_document->{'sections'};
	    
	    my $md_name_prefix = $tipple_locale->{'code'};
	    $md_name_prefix .= "_".$tipple_roles->[0]->{'type'} if defined $tipple_roles->[0]->{'type'};
	    
	    foreach my $tipple_section (@$tipple_sections) {
		my $md_val_caption = $tipple_section->{'caption'};
		my $md_val_content = $tipple_section->{'content'};
		
		if (defined $md_val_caption) {
		    my $md_name_caption = "${md_name_prefix}_caption";
		    $doc_obj->add_utf8_metadata($cursection,$md_name_caption,$md_val_caption);
		}
		
		if (defined $md_val_content) {
		    my $md_name_content = "${md_name_prefix}_content";
		    $doc_obj->add_utf8_metadata($cursection,$md_name_content,$md_val_content);
		}
	    }
	    
	}

	# .mediaItems
	#   .file
	#     .sourceUri
	#     .contentType
	

	my $tipple_media_items = $json_rec->{'mediaItems'};
	foreach my $tipple_media_item (@$tipple_media_items) {
	    my $tipple_file = $tipple_media_item->{'file'};
	    if (defined $tipple_file) {
		
		my $tipple_source_uri   = $tipple_file->{'sourceUri'};
		my $tipple_content_type = $tipple_file->{'contentType'};
		
		$doc_obj->add_utf8_metadata($cursection,"sourceUri",  $tipple_source_uri);
		$doc_obj->add_utf8_metadata($cursection,"contentType",$tipple_content_type);
		
	    }
	}
    }

    # $doc_obj->add_utf8_text($cursection, $$textref);
    $doc_obj->add_utf8_text($cursection, "<pre>\n$json_unicode_str\n</pre>");

    return 1;    
}

    

# sub print_error
# {

#     my $self = shift(@_);
#     my ($outhandle, $failhandle, $gli, $file, $error) = @_;

#     print $outhandle "TippleExportJSONPlugin Error: $file: $error\n";
#     print $failhandle "TippleExportJSONPlugin Error: $file: $error\n";
#     print STDERR "<ProcessingError n='$file' r='$error'/>\n" if ($gli);
# }

1;
