#!/usr/bin/perl
#
# This script starts off the whole shebang, by queuing up a 'fetch' process.
#

use strict;

use lib '/app/tools/bookpub/lib';
use lib '/app/tools/common/lib';

use BookPub::Catalog::Import::Job::Fetch;
use BookPub::Catalog::Import::Process::Fetcher::Factory;
use BookPub::DB::Item::CatalogImport;
use Common::Assert;
use Common::Log;
use Common::Process;
use Common::RSApp;
use Common::RSDB;
use Data::Dumper;
use Getopt::Std;

# Parse the command-line options.
#
my $gVerbosityLevel = 1;
my %gOptions;
my $gForceFlag = 0;

_parseCommandLine( \%gOptions );

my @clientIDs;

if ( 'ALL' eq $gOptions{clientID} ) {
    _getAllBookPubClientIDs( \@clientIDs );
} else {
    push @clientIDs, $gOptions{clientID};
}

foreach my $clientID (@clientIDs) {
    my $app = Common::RSApp->new( clientID => $clientID );

    # Make sure the previous import completed successfully,  unless
    # the 'force' flag was specified.
    #
    if ( !$gForceFlag ) {
        my $lastImportID = BookPub::DB::Item::CatalogImport->LastCatalogImportID();
        if ($lastImportID) {
            my $lastImport = BookPub::DB::Item::CatalogImport->Lookup( catalog_import_id => $lastImportID );
            if ($lastImport) {
                if ( BookPub::DB::Item::CatalogImport::kImportStatusDone() ne $lastImport->status() ) {
                    Common::Log::Print("Skipping client $clientID - Last import status not 'DONE'");
                    next;
                }
            }
        }
    }

    # Create a new catalog import record.
    #
    my $catalogImport = BookPub::DB::Item::CatalogImport->Create( status => BookPub::DB::Item::CatalogImport::kImportStatusFetchReady, );

    # BEFORE we save the record, though, I want to make sure there is actually some work to do.
    #
    my $fetchProcess =
      BookPub::Catalog::Import::Process::Fetcher::Factory::NewFetcher( importRecord => $catalogImport, logLevel => $gVerbosityLevel );
    my @waitingFiles = $fetchProcess->waitingFiles();
    if ( !scalar @waitingFiles ) {
        Common::Log::Print("Skipping client $clientID - No files waiting to be processed");
        next;
    }

    $catalogImport->save();

    # Now queue the job.
    #
    my $job = BookPub::Catalog::Import::Job::Fetch->new(
        importID => $catalogImport->catalog_import_id(),
        logLevel => $gVerbosityLevel,
    );

    $job->enqueue();

    # Record the new job id in the catalog import record
    #
    $catalogImport->fetch_job_id( $job->id() );
    $catalogImport->save();

    Common::Log::Print( "Job id " . $job->id . " queued for catalog import id " . $catalogImport->catalog_import_id() );
}

sub _getAllBookPubClientIDs {
    my ($arrayRef) = @_;

    # Need an application context for the moment...
    #
    my $app = Common::RSApp->new( clientID => 0 );

    # Just going to return those clients that have a Fetcher class declared.
    #
    my @ids = BookPub::Catalog::Import::Process::Fetcher::Factory::ValidClientIDs();
    push @$arrayRef, @ids;
}

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

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

    if ( !$opt{c} ) {
        _usage();
        exit(1);
    }

    $settings->{clientID} = $opt{c};

    if ( defined $opt{f} ) {
        $gForceFlag = 1;
    }

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

sub _usage {
    print "\nusage: $0 -c client_id [-V n] [-f]\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
    print "\t\t\t\t--> use ALL to specify all BookPub clients.\n";
    print "\t-f\t\t\tForce the import to run, irregardless of the status of the previous import.\n";
    print "\t\t\t\tBy default, we will not queue an import when the previous import does not have\n";
    print "\t\t\t\ta status of 'DONE'\n";
    print "\t-V <N>\t\t\tVerbosity level - 0 means no output\n";
}

