#!/usr/bin/perl

use strict;

use Data::Dumper;
use File::Path;
use File::Basename;
use Getopt::Std;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use lib '/app/tools/data_classes/lib';
use lib '/app/tools/mediaserve/lib';
use Common::Util;
use Common::RSApp;
use Common::Locale;
use Common::Log;
use Common::Assert;
use BookPub::Catalog::Import::ONIX;

use BookPub::DB::Item::Book;
use BookPub::DB::Item::BookContributor;
use BookPub::DB::Item::BookFormat;
use BookPub::DB::Item::BookSubject;
use BookPub::DB::Item::Product;
use BookPub::DB::Item::ProductType;
use BookPub::DB::Item::BookProduct;
use BookPub::DB::Item::Chapter;
use BookPub::DB::Item::Imprint;
use BookPub::DB::Item::ContributorRole;
use BookPub::DB::Item::Contributor;
use Client::Client;
use MediaServe::DB::Item::MediaFile;
use MediaServe::SFTP;
use MediaServe::Server;

use BookPub::DB::Item::BookProductImageFile;

use constant kMediaServerUser     => 'web';
use constant kMediaServerPassword => 'getImages';
use constant kMediaServerIdent    => undef;

my $gVerbosityLevel = 1;
my %gOptions;
_parseCommandLine( \%gOptions );

my $imageDirectoryPath = $gOptions{filePath};
assert($imageDirectoryPath);
die "ERROR - $imageDirectoryPath is not a directory" unless ( -d $imageDirectoryPath );
my $clientID = $gOptions{clientID};
assert($clientID);

my $app = Common::RSApp->new( clientID => $clientID );

# We're going to loop through all the files in the directory, and create
# all the state we need.  Then upload them.
#
my $imageFile;
opendir( IMAGES, $imageDirectoryPath ) or die "unable to open $imageDirectoryPath: $!";
while ( defined( $imageFile = readdir(IMAGES) ) ) {
    if ( $imageFile =~ /\.jpg$/i ) {
        print "found file: " . $imageDirectoryPath . "/" . $imageFile . "\n";

        my ( $isbn, $suffix ) = split( /\./, $imageFile );
        print "isbn: $isbn\n";

        # Find the book_product
        #
        my $bookProduct = BookPub::DB::Item::BookProduct->Lookup( isbn13 => $isbn );
        if ($bookProduct) {
            my $mediaFile = MediaServe::DB::Item::MediaFile->Create(
                filename        => $imageFile,
                storage_host_id => 1,
                dataroot_id     => 2,
                status          => 'pending',    # Set status to pending now, and to active after we transfer the images over.
            );
            $mediaFile->save();

            my $id = $mediaFile->media_file_id;

            # Create the book image file entry
            #
            my $imageFile = BookPub::DB::Item::BookProductImageFile->Create(
                book_product_id => $bookProduct->product_id,
                media_file_id   => $id,
                file_type       => 'original',
            );
            $imageFile->save();
        }
    }
}
closedir(IMAGES);

# So, what we're gonna to here is loop through all the 'pending' media files,
# find the corresponding book product images, then _if_ the image is available, upload it.
#
my $currentHost;

my $sftp = MediaServe::SFTP->new(
    user     => kMediaServerUser,
    password => kMediaServerPassword,
    identity => kMediaServerIdent,
);

my $imageFileList = BookPub::DB::Item::BookProductImageFile->GetAll();
while ( my $imageFile = $imageFileList->next() ) {
    my $mediaFileID = $imageFile->media_file_id;
    my $mediaFile = MediaServe::DB::Item::MediaFile->Lookup( media_file_id => $mediaFileID );
    if ( $mediaFile && 'pending' eq $mediaFile->status ) {

        # Find the file.
        #
        my $fullPath = $imageDirectoryPath . "/" . $mediaFile->filename;
        if ( -f $fullPath ) {
            Common::Log::Print("file: $fullPath  mediaFileID $mediaFileID");
            my ( $host, $path ) = MediaServe::Server::GetImagePath( clientID => Common::RSApp::GetClientID(), mediaFileID => $mediaFileID );

            # HARD CODE THIS PUPPY
            $host = 'cm01.royaltyshare.com';

            Common::Log::Print("path: $path");
            if ( !$currentHost || $host ne $currentHost ) {
                $sftp->close() if $currentHost;

                $currentHost = $host;
                Common::Log::Print("connecting to $currentHost");
                $sftp->connect($currentHost);
            }

            Common::Log::Print("mkdir");
            $sftp->mkdir( dirname($path) );
            Common::Log::Print("put");
            if ( !$sftp->put( $fullPath, $path ) ) {
                Common::Log::Print("- TRANSFER FAILED: $@");
            } else {
                Common::Log::Print("+ transfered");

                # Flag the media file record as 'active'

                $mediaFile->status('active');
                $mediaFile->save();
            }
        } else {
            Common::Log::Print("... cannot find $fullPath");
        }
    }
}

$sftp->close();

sub _parseCommandLine {
    my ($settings) = @_;

    my %opt;
    getopts( 'f:c:V:', \%opt );

    if ( !$opt{f} || !$opt{c} ) {
        _usage();
        exit(1);
    }
    $settings->{filePath} = $opt{f};
    $settings->{clientID} = $opt{c};

    if ( defined $opt{V} ) {
        $gVerbosityLevel = $opt{V};
    }
}

sub _usage {
    print "\nusage: $0 -c client_id -f path_to_XML_file [-V n]\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
    print "\t-f <path_to_XML_file>\tThe path to the XML file to parse\n";
    print "\t-V <N>\t\t\tVerbosity level - 0 means no output\n";
}

