#!/usr/bin/perl
#
# This script parses an ONIX file, and stages this data in a set of 'holding tables'.
# These holding tables have essentially the same schema as the metadata tables.
# Another process will come along later to analyze, validate, and (hopefully) move that
# data into the actual metadata tables.

use strict;

use Data::Dumper;
use Getopt::Std;
use POSIX qw(:sys_wait_h :signal_h :errno_h);

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use Common::Process;
use Common::RSApp;
use Common::Log;
use Common::Assert;
use Common::DB::Item;
use BookPub::DB::Item::CatalogImport;
use BookPub::DB::Item::CatalogImportItem::File;

# Parse the command-line options.
#
my $gVerbosityLevel = 1;
my %gOptions;
_parseCommandLine( \%gOptions );

my $gClientID = $gOptions{clientID};
assert($gClientID);

# make sure the file args are valid before we proceed...
#
my @files;
foreach my $file (@ARGV) {
    die "ERROR - arg $file is not a valid path" unless -f $file;
    push @files, $file;
}

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

# Create a new catalog import
#
my $newImport = BookPub::DB::Item::CatalogImport->Create( status => BookPub::DB::Item::CatalogImport::kImportStatusStagingReady, );
$newImport->save();

foreach my $file (@files) {
    my $newFile = BookPub::DB::Item::CatalogImportItem::File->Create(
        catalog_import_id => $newImport->catalog_import_id(),
        file_path         => $file,
    );
    $newFile->save();
}

print "CATALOG IMPORT ID:" . $newImport->catalog_import_id . "\n";

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

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

    if ( !$opt{c} ) {
        _usage();
        exit(1);
    }
    $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-V <N>\t\t\tVerbosity level - 0 means no output\n";
}

