#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#---------------------------------------------------------------
package BookPub::Catalog::Import::Process::Fetcher::FileHandler::ZipArchive::ONIX;
use strict;
use warnings;

use File::Path;
use Data::Dumper;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use Common::Assert;
use BookPub::DB::Item::CatalogImportItem::File;

use base 'BookPub::Catalog::Import::Process::Fetcher::FileHandler::ZipArchive';

sub _preExtract {
    my ($self) = @_;

    $self->SUPER::_preExtract();

    # What I want to do is figure out what the name of the extracted file will be.
    # I can probably guess it, but I might be wrong.
    #
    # !!! the path to zipinfo should probably be in Config...
    #
    # The '-1' options means to just list the file name - see 'man zipinfo' for more info.
    #
    my $zipInfoCommand = "/usr/bin/zipinfo -1 " . $self->localFile();

    # !!! I kinda like using the open pipe method, rather than backticks.
    # !!! I feel like it's easier to parse out errors and stuff, but it probably
    # !!! doesn't make that much of a difference...
    my @filenames;
    open( ZIPINFO, "$zipInfoCommand |" ) or die "ERROR : unable to run $zipInfoCommand: $!";
    while ( my $filename = <ZIPINFO> ) {
        chomp $filename;

        # Invoking a virtual method to filter out files from the archive we might want to ignore.
        #
        next unless $self->_validFilename($filename);
        push @filenames, $filename;
    }
    close(ZIPINFO);

    if ( !scalar @filenames ) {
        die "ERROR - no files were extracted from onix zip archive: " . $self->localFile();
    }

    # Remember that these won't have the full path...
    #
    $self->{_extractedFileNames} = \@filenames;
}

sub _validFilename {
    my ( $self, $filename ) = @_;

    # By default, all files found in the archive are 'valid'.
    #
    return 1;
}

sub _postExtract {
    my ($self) = @_;

    my $catalogImportID = $self->{_fetcher}->_catalogImportID();

    foreach my $filename ( @{ $self->{_extractedFileNames} } ) {
        my $fullPath = $self->{_localDirectory} . "/$filename";

        if ( !-e $fullPath ) {
            die "ERROR - did not find expected extracted file at $fullPath";
        }

        my $importFileRec = BookPub::DB::Item::CatalogImportItem::File->Create(
            catalog_import_id => $catalogImportID,
            file_path         => $fullPath,
        );
        $importFileRec->save();
    }
}

1;
