#!/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 );

    # 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;
    } else {
        Common::Log::Print("client $clientID");
        foreach my $file (@waitingFiles) {
            Common::Log::Print("   $file");
        }
    }
}

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";
}

