#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#---------------------------------------------------------------
package BookPub::Catalog::Import::Process::ImageRetriever::Base;
use strict;
use warnings;
use Data::Dumper;
use File::Path;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use lib '/app/tools/mediaserve/lib';
use Common::RSApp;
use Common::Util;
use Common::Assert;
use Common::Process;
use Common::Client;
use Common::DB::Item::Language;
use BookPub::DB::Item::CatalogImport;
use BookPub::Config;
use MediaServe::DB::Item::MediaFile;

use base 'BookPub::Catalog::Import::Process';

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

    $self->_report( "entering BookPub::Catalog::Import::Process::ImageRetriever::run", 3 );

    # Set the catalogImportID in the Application singleton, so that we'll have
    # that ID available in the table_change_log.
    #
    Common::RSApp::GetRAMCache()->{catalogImportID} = $self->_catalogImportID();

    # So... how is this going to work?
    # I am tempted to let this process be file driven.
    # Just point this thing at a directory and let it do it's stuff.
    # Which could involve:
    # - copying the image file to the 'ingestion' directory.
    # - invoking wget to fetch the file, then copying that to the ingestion directory.
    #

    my $dirPath = $self->_imageSourceDirectory();

    my $IMAGE_SRC;

    if ( opendir( $IMAGE_SRC, $dirPath ) ) {
        while ( my $file = readdir($IMAGE_SRC) ) {
            next if ( '.' eq substr( $file, 0, 1 ) );
            next if ( '_' eq substr( $file, 0, 1 ) );

            $self->_handleFile($file);
        }

        closedir($IMAGE_SRC);
    }

    # !!! If I run this on the appropriate web server, then I can kick off the 'process_books' script to finish the job.
    #

    return 0;
}

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

    return $self->_getBaseStagingPath() . "/images/";
}

sub _handleFile {
    my ( $self, $file ) = @_;

    # If we already have a media file for this ISBN, let's skip it.
    if ( $file =~ /^(d{13})\./ ) {
        my $filename = $1 . ".jpg";
        my $alreadyHaveIt = MediaServe::DB::Item::MediaFile->Lookup( filename => $filename );

        if ($alreadyHaveIt) {
            return;
        }
    }

    if ( $file =~ /\.jpg$/i ) {
        $self->_handleJPGFile($file);
    }

    if ( $file =~ /\.url$/i ) {
        $self->_handleURLFile($file);
    }
}

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

    if ( !$self->{_ingestionPath} ) {
        my $config = $self->_config();

        my $basePath      = $config->get('catalog_import_image_ingestion_dir');
        my $ingestionPath = $basePath . Common::RSApp::GetClientID() . '/upload/';

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

        $self->{_ingestionPath} = $ingestionPath;
    }

    return $self->{_ingestionPath};
}

sub _handleJPGFile {
    my ( $self, $file ) = @_;

    # Just copy the file to the 'ingestion' directory.
    # We'll create a _tmp directory to catch the file as it downloads.
    #
    my $ingestionDir = $self->_getIngestionDir();
    my $sourcePath   = $self->_imageSourceDirectory();
    `cp $sourcePath/$file $ingestionDir`;
}

sub _handleURLFile {
    my ( $self, $file ) = @_;

    my $ingestionDir = $self->_getIngestionDir();

    # Download the url, then move the resulting file into the ingestion directory.
    #
    my $sourcePath = $self->_imageSourceDirectory();
    my $tmpPath    = "$sourcePath/_tmp";
    if ( !-d $tmpPath ) {
        File::Path::mkpath($tmpPath) || die "ERROR - unable to create directory $tmpPath : $!";
    }

    if ( $file =~ /^(\d*)\.url/i ) {
        my $isbn = $1;

        # The first line of the file should be a url.
        #
        if ( open INFILE, "$sourcePath/$file" ) {
            my $url = <INFILE>;
            close INFILE;
            chomp $url;

            my $destFilePath = "$tmpPath/$isbn.jpg";
            $self->_downloadURL( $url, $destFilePath );

            # !!! For now assume it worked.
            # Actually, make sure that a) the file exists and b) it isn't empty...
            #
            if ( -s $destFilePath ) {
                $self->_report( " copying $destFilePath to $ingestionDir/$isbn.jpg", 3 );
                `cp $destFilePath $ingestionDir/$isbn.jpg`;
            } else {
                $self->_report(" unable to copy $destFilePath to $ingestionDir/$isbn.jpg - File is empty or missing");
            }
        }
    }

}

sub _downloadURL {
    my ( $self, $url, $destFilePath ) = @_;

    $self->_report( " fetching url: $url  to destination $destFilePath", 3 );
    `/usr/bin/wget -q -O $destFilePath '$url'`;
}

###
1;    #
###
