###########################################################################
#
# MusicIRPlugin.pm -- for augmenting audio/midi files with Music IR 
#                     features and tags
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 1999 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 MusicIRPlugin;

use BaseImporter;
use jAudioExtractor;
use jSongMinerExtractor;
use pEssentiaExtractor;

use strict;
no strict 'refs'; # allow filehandles to be variables and viceversa
no strict 'subs';

use gsprintf 'gsprintf';

sub BEGIN {
    @MusicIRPlugin::ISA = ('BaseImporter', 'jAudioExtractor', 'jSongMinerExtractor', 'pEssentiaExtractor');
}

my $arguments =
    [ 
      { 'name' => "compute_mir_features",
	'desc' => "{BaseImporter.compute_mir_features}",
	'type' => "enum",
	'list' => [{'name' => "true",  'desc' => "{common.true}"},
		   {'name' => "false", 'desc' => "{common.false}"}],
	'deft' => "false",
	'reqd' => "no" },
      { 'name' => "compute_essentia_features",
	'desc' => "{BaseImporter.compute_essentia_features}",
	'type' => "enum",
	'list' => [{'name' => "true",  'desc' => "{common.true}"},
		   {'name' => "false", 'desc' => "{common.false}"}],
	'deft' => "false",
	'reqd' => "no" },
      { 'name' => "retrieve_mir_metadata",
	'desc' => "{BaseImporter.retrieve_mir_metadata}",
	'type' => "enum",
	'list' => [{'name' => "true",  'desc' => "{common.true}"},
		   {'name' => "false", 'desc' => "{common.false}"}],
	'deft' => "false",
	'reqd' => "no" },
      { 'name' => "process_exp",
	'desc' => "{BaseImporter.process_exp}",
	'type' => "regexp",
	'deft' => &get_default_process_exp(),
	'reqd' => "no" }
      ];

my $options = { 'name'     => "MusicIRPlugin",
		'desc'     => "{MusicIRPlugin.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 $jae_self = new jAudioExtractor($pluginlist, $inputargs, $hashArgOptLists,1);
    my $jsme_self = new jSongMinerExtractor($pluginlist, $inputargs, $hashArgOptLists,1);
    my $pee_self = new pEssentiaExtractor($pluginlist, $inputargs, $hashArgOptLists,1);

    my $base_self = new BaseImporter($pluginlist, $inputargs, $hashArgOptLists);

    my $self = BaseImporter::merge_inheritance($jae_self,$jsme_self,$base_self);

    return bless $self, $class;
}

sub get_default_process_exp {
    my $self = shift (@_);
    
    return q^(?i)(\.mp3|\.wave?|\.aif[fc]?|\.au|\.snd|\.og[ga]|\.m4a)$^; 
}

sub begin {
    my $self = shift (@_);
    my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;

    $self->SUPER::begin(@_);
    $self->jAudioExtractor::begin(@_);
    $self->jSongMinerExtractor::begin(@_);
    $self->pEssentiaExtractor::begin(@_);
}




sub process_features {
    my $self = shift (@_);
    my ($base_dir, $file, $doc_obj) = @_;

    my $outhandle = $self->{'outhandle'};
    my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);

    my $top_section = $doc_obj->get_top_section();

    if ($self->{'compute_mir_features'} eq "true")
    {
	my $utf8_filename_no_path = $self->filepath_to_utf8($filename_no_path);
	my $url_encoded_filename = &util::rename_file($utf8_filename_no_path, $self->{'file_rename_method'});
	
	my $features_filename = $self->compute_features($filename_full_path);
	my ($features_ext) = ($features_filename =~ m/\.([^.]+)$/);

	
	my $mime_type = ($features_ext eq "arff") ? "text/plain" : "text/xml";
	$doc_obj->associate_file($features_filename, "jaudio.$features_ext", 
				 $mime_type, $top_section);

    }

    if ($self->{'compute_essentia_features'} eq "true")
    {
	my $utf8_filename_no_path = $self->filepath_to_utf8($filename_no_path);
	my $url_encoded_filename = &util::rename_file($utf8_filename_no_path, $self->{'file_rename_method'});
	
	my $features_filename = $self->compute_essentia_features($filename_full_path);
	my ($features_ext) = ($features_filename =~ m/\.([^.]+)$/);

	
	my $mime_type = ($features_ext eq "json") ? "application/json" : "text/plain";
	$doc_obj->associate_file($features_filename, "pessentia.$features_ext", 
				 $mime_type, $top_section);

    }

}

# do plugin specific processing of doc_obj
sub process {
    my $self = shift (@_);
    my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;

    my $top_section = $doc_obj->get_top_section();

    $self->process_features($base_dir,$file,$doc_obj);
    
    #we have no text - adds dummy text and NoText metadata
    $self->add_dummy_text($doc_obj, $doc_obj->get_top_section());

    my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
    $doc_obj->associate_file($filename_full_path, "audio.mp3", "audio/mpeg", $top_section);

    return 1;

}

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

    my $outhandle = $self->{'outhandle'};
    my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);

    if ($self->{'retrieve_mir_metadata'} eq "true") {
	my $top_section = $doc_obj->get_top_section();

	my $id3_titles = $doc_obj->get_metadata($top_section,"ex.ID3.Title");
	# my $id3_title = shift @$id3_titles || "Unknown";
	my $id3_title = shift @$id3_titles || undef;

	my $id3_artists = $doc_obj->get_metadata($top_section,"ex.ID3.Artist");
	# my $id3_artist = shift @$id3_artists || "Unknown";
	my $id3_artist = shift @$id3_artists || undef;

	my ($metadata_acexml_filename,$metadata_txt_filename) 
	    = $self->retrieve_metadata($filename_full_path,$id3_title,$id3_artist);
	
	if (-e $metadata_txt_filename) {
	    $self->parse_txt_metadata($doc_obj,$metadata_txt_filename);
	}

	### $self->check_for_existing_id3_genre($doc_obj);

	$doc_obj->associate_file($metadata_acexml_filename, "jsongminer.xml", 
				 "text/xml", $top_section);
    }


    return 1;
}


1;



