#!/usr/bin/perl
#------------------------------------------------------------ 
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------ 
use strict;

use Data::Dumper;
use Getopt::Std;
use POSIX qw(ceil);
use Carp;

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

use lib '/app/tools/raptor/lib';
use Raptor::DB::Item::Sale;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::Statement::Artist::PDF;
use RPS::DB::Item::ArtistRoyaltyRunMissedSaleLog;
use RPS::DB::Item::ArtistRoyaltyStatement;
use RPS::DB::Item::ArtistRoyaltyTransaction;
use RPS::DB::Item::ArtistRoyaltyIncomeItem;
use RPS::DB::Item::ArtistRoyaltyLicenseIncomeItem;
use RPS::DB::Item::ArtistRoyaltyExpenseItem;
use RPS::DB::Item::ArtistRoyaltyAlbum;
use RPS::DB::Item::SaleRunMap;
use RPS::DB::Item::ArtistContractTermReserveRun;
use RPS::DB::Item::ArtistContractTermReserve;
use RPS::DB::Item::ArtistRoyaltyRunMissedSaleLog;
use RPS::DB::Item::ReportQueries::ArtistReservePipeline;
use RPS::RoyaltyRun::Status;

my $gVerbosityLevel = 1;

# Get the id from the command-line
#
my %options;
_parseCommandLine(\%options);
_deleteRun($options{clientID}, $options{runID});



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

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

    if (! $opt{r} || ! $opt{c})
    {
        _usage();
        exit(1);
    }
    $settings->{runID} = $opt{r};
    $settings->{clientID} = $opt{c};
    if ($opt{V})
    {
        $gVerbosityLevel = $opt{V};
    }
}

sub _usage
{
    print "\nusage: $0 -c client_id -r run_id\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
    print "\t-r <run_id>\t\tThe artist_royalty_run_id of the artist royalty run to delete\n";
}


sub _deleteRun
{
    my ($clientID, $runID) = @_;
    assert($clientID);
    assert($runID);

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


    # Get the run - we need to check it's status to make sure we can delete it.
    #
    my $run = RPS::DB::Item::ArtistRoyaltyRun->Lookup(artist_royalty_run_id => $runID);
    if (! $run)
    {
        die "ERROR - cannot find artist royalty run with id $runID\n";
    }


    if (RPS::RoyaltyRun::Status::kCommitted == $run->status)
    {
        die "ERROR - run $runID has already been committed, and cannot be deleted\n";
    }


    # Clear out the log tables
    #
    RPS::DB::Item::ArtistRoyaltyRunMissedSaleLog->DeleteByRunID($runID);


	# Delete the reserves.
	#
    RPS::DB::Item::ArtistContractTermReserve->DeleteByArtistRoyaltyRunID($runID);
    RPS::DB::Item::ArtistContractTermReserveRun->DeleteByArtistRoyaltyRunID($runID);

    # Get all of the statements created by this run,
    # and delete them.
    #
    my $statements = RPS::DB::Item::ArtistRoyaltyStatement->GetByArtistRoyaltyRunID($runID);

    while ($statements->hasNext())
    {
        my $statement = $statements->next();
        _deleteStatement($statement);
    }


    # delete reserves created by this run
    #
#    my $reserveMapItems = RPS::DB::Item::ArtistContractTermReserveRun->GetByArtistRoyaltyRunID($runID);
#    while (my $reserveMap = $reserveMapItems->next())
#    {
#        my $reserve = RPS::DB::Item::ArtistContractTermReserve->Lookup
#        (   
#            artist_contract_term_reserve_id => $reserveMap->artist_contract_term_reserve_id,
#        );
#        if ($reserve && 0 == $reserve->next_period())
#        {
#            $reserve->delete();
#        }
#    }


    # Delete the pdf statements
    #
    my $pdfPath = RPS::Statement::Artist::PDF::StatementPathFromRunID($runID);
    if (-d $pdfPath)
    {
        system("rm -rf $pdfPath");
    }

    # Delete this run from the run table.
    #
    _report("deleting from artist royalty run table");
    $run->delete();
#    RPS::DB::Item::ArtistRoyaltyRun::DeleteArtistRoyaltyRun($runID);


    # Delete sale map entries
    #
    _report("deleting from sale map");
    RPS::DB::Item::SaleRunMap->DeleteByArtistRoyaltyRunID($runID);


    # Delete the reports
    #
    RPS::DB::Item::ArtistRoyaltyRunMissedSaleLog->DeleteByRunID($runID);
    RPS::DB::Item::ReportQueries::ArtistReservePipeline->DeleteByArtistRoyaltyRunID($runID);

}




sub _deleteStatement
{
    my ($statement) = @_;

    my $statementID = $statement->artist_royalty_statement_id;


    _report("deleting statement $statementID");
    $statement->delete();


    my $albums = RPS::DB::Item::ArtistRoyaltyAlbum->GetByArtistRoyaltyStatementID($statementID);
    while (my $album = $albums->next())
    {
        my $albumID = $album->artist_royalty_album_id;

        # Delete the income and expense items
        #
        _report("  ... deleting income items",2);
        RPS::DB::Item::ArtistRoyaltyIncomeItem->DeleteByArtistRoyaltyAlbumID($albumID);
        _report("  ... deleting expense items",2);
        RPS::DB::Item::ArtistRoyaltyExpenseItem->DeleteByArtistRoyaltyAlbumID($albumID);

    }

    _report("  ... deleting license income items",2);
    RPS::DB::Item::ArtistRoyaltyLicenseIncomeItem->DeleteByArtistRoyaltyStatementID($statementID);

    # Delete all the album items
    #
    _report("  ... deleting artist royalty albums",2);
    RPS::DB::Item::ArtistRoyaltyAlbum->DeleteByArtistRoyaltyStatementID($statementID);


    # Delete the transaction items
    _report("  ... deleting artist royalty transactions",2);
    RPS::DB::Item::ArtistRoyaltyTransaction->DeleteByArtistRoyaltyStatementID($statementID);
}


sub _report
{
    my ($string, $verbosity) = @_;
    $verbosity = 1 unless defined $verbosity;

    if ($gVerbosityLevel >= $verbosity)
    {
        print STDERR $string . "\n";
    }
}

