#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
#!/usr/bin/perl

use strict;
use Data::Dumper;

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

use lib '/app/tools/rps/lib/';
use RPS::DB::Item::License;
use RPS::DB::Item::TrackLicense;
use RPS::DB::Item::ControlledCompositionLicense;
use RPS::DB::Item::LicenseReserveLiquidation;

# Instantiate the application singleton object.
#
my $clientID = $ARGV[0];
unless ( $clientID =~ /^\d+$/ && $clientID > 0 ) {
    die usage("You must specify a valid client ID");
}

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

my %idMap;
collapse_track_license_table( \%idMap );
convert_reserves( \%idMap );

sub collapse_track_license_table {
    my ($idMap) = @_;

    my $trackLicenses = RPS::DB::Item::TrackLicense->GetAll();

    print "track_licenses to convert: " . $trackLicenses->size() . "\n";
    my $count = 0;
    while ( $trackLicenses->hasNext() ) {
        my $trkLicense = $trackLicenses->next();

        # Fetch the appropriate stuff.
        # We don't need to do anything to public domain or unknown publisher entries.
        #
        if ( RPS::DB::Item::TrackLicense::kPublishingLicense == $trkLicense->type ) {

            # Fetch the license data.
            #
            my $license = RPS::DB::Item::License->Lookup( license_id => $trkLicense->id );
            if ($license) {
                $trkLicense->publisher_direct( $license->publisher_direct() );
                $trkLicense->date_sent( $license->date_sent() );
                $trkLicense->date_received( $license->date_received() );
                $trkLicense->date_issued( $license->date_issued() );
                $trkLicense->term_start( $license->term_start() );
                $trkLicense->term_end( $license->term_end() );
                $trkLicense->rate_basis( $license->rate_basis() );
                $trkLicense->rate_type( $license->rate_type() );
                $trkLicense->issuer_license_id( $license->issuer_license_id() );
                $trkLicense->advance_account_id( $license->advance_account_id() );
                $trkLicense->product_type_id( $license->product_type_id() );
                $trkLicense->date_created( $license->date_created() );
                $trkLicense->created_by( $license->created_by() );
                $trkLicense->date_modified( $license->date_modified() );
                $trkLicense->modified_by( $license->modified_by() );
                $trkLicense->penny_rate( $license->penny_rate() );
                $trkLicense->advance_amount( $license->advance_amount() );
                $trkLicense->reserve_percentage( $license->reserve_percentage() );
                $trkLicense->percentage_of_sales( $license->percentage_of_sales() );
                $trkLicense->packaging_deduction( $license->packaging_deduction() );
                $trkLicense->free_goods( $license->free_goods() );
                $trkLicense->misc_deduction( $license->misc_deduction() );

                $idMap{1}{ $trkLicense->id } = $trkLicense->track_license_id;
            } else {
                print "!!! track_license " . $trkLicense->track_license_id . " : can't load license " . $trkLicense->id . " !!!\n";
            }
        } elsif ( RPS::DB::Item::TrackLicense::kControlledComposition == $trkLicense->type ) {
            my $ccomp = RPS::DB::Item::ControlledCompositionLicense->Lookup( controlled_composition_license_id => $trkLicense->id );
            if ($ccomp) {
                $trkLicense->controlled_composition_id( $ccomp->controlled_composition_id() );
                $trkLicense->publisher_direct( $ccomp->publisher_direct() );
                $trkLicense->date_sent( $ccomp->date_sent() );
                $trkLicense->date_received( $ccomp->date_received() );
                $trkLicense->date_issued( $ccomp->date_issued() );
                $trkLicense->term_start( $ccomp->term_start() );
                $trkLicense->term_end( $ccomp->term_end() );
                $trkLicense->issuer_license_id( $ccomp->issuer_license_id() );

                $idMap{2}{ $trkLicense->id } = $trkLicense->track_license_id;
            } else {
                print "!!! track_license " . $trkLicense->track_license_id . " : can't load ccomp_license" . $trkLicense->id . " !!!\n";
            }
        }

        $trkLicense->save();

        $count++;
        if ( 0 == $count % 100 ) {
            print "... $count\n";
        }
    }

    print "Converted $count track_licenses.\n";
}

sub convert_reserves {
    my ($idMap) = @_;

    # This is _slightly_ trickier.  Need to convert the license_reserve_liquidation
    # table to use track_license_id instead of license_id.
    #

    # We'll make two passes - First, we'll read the existing table and delete records as we go
    # Then we'll insert the new entries.
    # This is to avoid key collisions.
    #
    print "Reading existing license_reserve_liquidation table...\n";
    my @newRecords;
    foreach my $type ( keys %$idMap ) {
        my $innerMap = $idMap->{$type};
        foreach my $licenseID ( keys %$innerMap ) {
            my $trackLicenseID = $innerMap->{$licenseID};

            my $collection = RPS::DB::Item::LicenseReserveLiquidation::GetLicenseReserveLiquidationsByLicenseID( $licenseID, $type );
            while ( my $orig = $collection->next() ) {
                my $new = RPS::DB::Item::LicenseReserveLiquidation->Create(
                    license_id             => $trackLicenseID,
                    type                   => $orig->type(),
                    period                 => $orig->period(),
                    liquidation_percentage => $orig->liquidation_percentage(),
                );
                $orig->delete();

                push @newRecords, $new;
            }
        }
    }

    print "Creating new license_reserve_liquidation table...\n";
    foreach my $newRecord (@newRecords) {
        $newRecord->save();
    }
}

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

