#!/usr/bin/perl
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 BookPub::DB::Item::Book;
use BookPub::DB::Item::BookProduct;
use BookPub::DB::Item::Imprint;
use BookPub::DB::Item::Publisher;
use BookPub::Catalog::ProductFormat;

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

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

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

# Let's go alphabetical by book title.
# They want: title, ISBN, Format, Imprint, Publisher
#
# Yeah, I might be able to do this with a single gnarly query.  But why?
#
my %gImprint;
my $allImprints = BookPub::DB::Item::Imprint->GetAll();
while ( my $imprint = $allImprints->next() ) {
    $gImprint{ $imprint->imprint_id() } = $imprint->name;
}

my %gPublisher;
my $allPublishers = BookPub::DB::Item::Publisher->GetAll();
while ( my $publisher = $allPublishers->next() ) {
    $gPublisher{ $publisher->publisher_id() } = $publisher->name;
}

my $allBooks = BookPub::DB::Item::Book->GetAll("SELECT * FROM book ORDER BY title");
while ( my $book = $allBooks->next() ) {
    my $allBookProducts = BookPub::DB::Item::BookProduct->GetAllByBookID( $book->book_id );
    while ( my $bookProduct = $allBookProducts->next() ) {
        my $format = BookPub::Catalog::ProductFormat->new( bookFormatID => $bookProduct->book_format_id );

        print $book->title() . "\t"
          . $bookProduct->isbn13() . "\t"
          . $format->asString() . "\t"
          . $gImprint{ $bookProduct->imprint_id() } . "\t"
          . $gPublisher{ $bookProduct->publisher_id() } . "\n";
    }
}

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

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

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

sub _usage {
    print "\nusage: $0 -c client_id \n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
}

