#!/usr/bin/perl

use strict;
use Getopt::Std;
use IO::File;
use Date::Calc;
use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::RSDB;
use Common::RSApp;
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::Expense;
use RPS::DB::Item::ExpenseType;
use RPS::DB::Item::ExpenseName;

=begin
select nac.artist_contract_id, ac.album_contract_id
from new_artist_contract nac, artist_payee ap, album_contract ac, album a
where nac.artist_payee_id=ap.artist_payee_id
  and a.album_id=ac.album_id
  and ac.artist_contract_id=nac.artist_contract_id
  and a.catalog_number='HMU 907231'
  and ap.client_account_id='2120-1029';
=cut

# Parse the command-line.
#
my ( $clientID, $inputFile ) = parseCommandLine();

$| = 1;

my $rsdb = Common::RSDB->new( client_id => $clientID );

# Instantiate the application singleton object.
#
my $appSingleton = Common::RSApp->new( clientID => $clientID );

# create expense name
#
my $expenseNameObj = RPS::DB::Item::ExpenseName->Lookup( name => "Advance" );

if ( !$expenseNameObj ) {
    $expenseNameObj = RPS::DB::Item::ExpenseName->Create( name => "Advance" );
    $expenseNameObj->save();
}

my $matched   = 0;
my $unmatched = 0;
my $skipped   = 0;

my $sql = "
select nac.artist_contract_id, ac.album_contract_id
from new_artist_contract nac, artist_payee ap, album_contract ac, album a
where nac.artist_payee_id=ap.artist_payee_id
  and a.album_id=ac.album_id
  and ac.artist_contract_id=nac.artist_contract_id
  and a.catalog_number like ?
  and ap.client_account_id=?
";
my %contractExpenseType = ();
open( F, $inputFile ) or die "oops $!\n";
while (<F>) {
    chop;
    s/"//g;
    my ( $acctID, $title, $amount, $junk, $payeeID, $note, $catID ) = split /\t/;
    my @fields = split /\t/;

    if ( $amount == 0 ) {
        $skipped++;
        next;
    }

    $catID = "%$catID" unless ( $catID =~ m/^4/ );
    my $sth = $rsdb->DoCmdWithPlaceholders( $sql, [ $catID, $payeeID ] );
    unless ( $sth->rows ) {
        print "no match for cat: $catID, payee: $payeeID\n";
        $unmatched++;
        next;
    }

    if ( $sth->rows > 1 ) {
        print "multimatch $catID $payeeID\n";
        next;
    }

    $matched++;
    my ( $artistContractID, $albumContractID ) = $sth->fetchrow_array();
    print "found match for cat: $catID, payee $payeeID ($artistContractID, $albumContractID)\n";

    #next;

    if ( !$contractExpenseType{$artistContractID} ) {

        # create an expense type for advance
        #
        my $newExpenseType = RPS::DB::Item::ExpenseType->Create(
            artist_contract_id => $artistContractID,
            expense_name_id    => $expenseNameObj->expense_name_id,
            percent            => 100,
        );
        $newExpenseType->save();
        $contractExpenseType{$artistContractID} = $newExpenseType->expense_type_id;
    }

    my %params = (
        expense_type_id => $contractExpenseType{$artistContractID},
        amount          => $amount,
        parent_type     => RPS::DB::Item::Expense::kParentAlbumContract(),
        parent_id       => $albumContractID,

        # usually this would be copied from the expense type, but we'll just hard code it here because we know it should always be 100
        percent => 100,
        memo    => $note,
    );
    my $newExpense = RPS::DB::Item::Expense->Create(%params);
    $newExpense->save();
}

print "skipped: $skipped\nunmatched: $unmatched\nmatched: $matched\n";

sub parseCommandLine {
    my %opt;
    getopts( 'c:f:', \%opt );

    my $clientID  = $opt{c};
    my $inputFile = $opt{f};

    unless ( $clientID =~ /^\d+$/ && $clientID > 0 ) {
        die usage("You must specify a valid client ID");
    }

    unless ($inputFile) {
        die usage("You must specify a catalog file to import");
    }

    unless ( -e $inputFile ) {
        die usage("The specified catalog file does not exist");
    }

    return ( $clientID, $inputFile );
}

sub usage {
    my $errstr = shift;
    my $text = ($errstr) ? "ERROR: $errstr\n" : '';
    $text .= "Usage: $0 -c <clientID> -f <inputFile>\n";
    return $text;
}

