#!/usr/bin/perl

use strict;

$| = 1;

use Getopt::Long;
use Data::Dumper;
use File::Path;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::RSDB;
use Common::RSApp;
use Common::Util qw(formatFixedPoint);

use lib '/app/tools/rps/lib';
use RPS::DB::Item::LabelContract;
use RPS::DB::Item::LabelContractTerm;
use RPS::DB::Item::LabelContractGroupTerm;
use RPS::DB::Item::LabelContractGroupTermLabel;

my %args = ();
parseCommandLine( \%args );

my @clientIDs;
if ( $args{clientID} ) {
    push @clientIDs, $args{clientID};
} else {
    @clientIDs = Common::RSDB::GetAllRPSClientIDs();

    #@clientIDs = Common::RSDB::GetLocalRPSClientIDs();
}

foreach my $clientID (@clientIDs) {
    print STDERR "processing client ID $clientID\n";
    my $appSingleton = Common::RSApp->new( clientID => $clientID );
    my $dbo          = Common::RSApp::GetClientDB();
    my $dbh          = $dbo->DBH;

    my $cdbo = Common::RSApp::GetCommonDB();
    my $cdbh = $cdbo->DBH;

    # Convert the label contract terms
    my $contracts = RPS::DB::Item::LabelContract->GetAll();
    while ( $contracts->hasNext() ) {
        my $contract = $contracts->next();
        processContract( $contract->label_contract_id );
    }

    # Rename the old table
    $dbo->DoCmd('RENAME TABLE label_contract_term TO old_label_contract_term');
}

#==============
#
# Subroutines
#
#==============

sub processContract {
    my $contractID = shift;
    my $terms      = RPS::DB::Item::LabelContractTerm->GetByLabelContractID($contractID);
    while ( $terms->hasNext() ) {
        my $term = $terms->next();
        my $groupTermID;
        my $distFee = $term->distribution_fee;
        my $labelID = $term->label_id;

        # Let's check for an existing group term with the same dist fee and label contract id
        my $existingGroupTerms = RPS::DB::Item::LabelContractGroupTerm->GetByLabelContractID($contractID);
        while ( $existingGroupTerms->hasNext() ) {
            my $existingGroupTerm = $existingGroupTerms->next();
            if ( $existingGroupTerm->distribution_fee == $distFee ) {
                $groupTermID = $existingGroupTerm->label_contract_group_term_id;
            }
        }

        # If we don't find a match, we'll have to add a new group term
        if ( !$groupTermID ) {
            my $newGroupTerm = RPS::DB::Item::LabelContractGroupTerm->Create(
                label_contract_id => $contractID,
                distribution_fee  => $distFee,
            );
            $newGroupTerm->save();
            $groupTermID = $newGroupTerm->label_contract_group_term_id;
        }

        # If we don't have a group term ID at this point, something has gone horribly wrong.
        if ( !$groupTermID ) {
            die "Missing group term id!";
        }

        # Now all that's left is to add the entry for this label
        my $newGroupTermLabel = RPS::DB::Item::LabelContractGroupTermLabel->Create(
            label_contract_group_term_id => $groupTermID,
            label_id                     => $labelID,
        );
        $newGroupTermLabel->save();
    }
}

sub parseCommandLine {
    my ($a) = @_;
    my $clientID;
    my $labelContractID;
    GetOptions( 'c|client_id=i' => \$clientID, );
    ${ _ [0] }{clientID} = $clientID;

}    #parseCommandLine

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

1;
