#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#---------------------------------------------------------------
package BookPub::Catalog::Import::Process::Fetcher::FileHandler::ZipArchive;
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 base 'BookPub::Catalog::Import::Process::Fetcher::FileHandler';

# So, we will want to uncompress the zip archive.
# However, we will want to be careful regarding where these files end up.
# I imagine that subclasses will need to provide a local directory to put them.
#
sub _processLocalFile {
    my ($self) = @_;

    # Do nothing.

    $self->_preExtract();
    $self->_extract();
    $self->_postExtract();
}

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

    # Generally, we will want to use the '-d' option and specify a location to unzip these files.
    # To be safe, we'll attempt to create that directory first...
    #
    my $extractDirectory = $self->_getExtractDirectory();
    assert($extractDirectory);

    if ( !-d $extractDirectory ) {
        File::Path::mkpath($extractDirectory) || die "ERROR - unable to create extract directory $extractDirectory : $!";
    }
}

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

    # The default will be the normal local directory.  Override this
    # if you want to put files into a subdirectory (or someplace else entirely).
    #
    return $self->{_localDirectory};
}

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

    # We'll shell out to do the unzipping.
    #
    # Added "-n" to let the script know not to overwrite anything.
    my $zipCommand = "/usr/bin/unzip -n " . $self->localFile() . " -d " . $self->_getExtractDirectory();
    my $exitStatus = system($zipCommand);

    # A non-0 exit status indicates an error occured.
    # In theory, since we used 'system', any error output that unzip wrote to STDERR should be sitting in
    # our log file already...
    #
    if ($exitStatus) {
        die "ERROR - an error occured executing '$zipCommand', exit code $exitStatus";
    }
}

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

    # We don't do anything by default.
    # Override this to rename files, create catalog_import_file records, etc.
    # I imagine the trick will be to figure out which files to mess around with.
    # If you put the files into their own unique subdirectory, that's not too challenging.
    # Otherwise, you might want to override _preExtract to interrogate the zip file and
    # get its manifest...
    #
}

1;
