#!/usr/bin/perl 

use strict;

use Getopt::Std;
use File::Basename;

my %opt;
usage() unless getopts( 'c:r:x:qhldv', \%opt );

if ( $opt{l} ) {
    list_clients( $ARGV[0] );
}

if ( $opt{h} ) {
    usage();
}

my $controller = new RemapSource(
    client_id => $opt{c},
    quiet     => $opt{q},
    verbose   => $opt{v},
    debug     => $opt{d}
);

$controller->run();

sub usage {
    my $prog = basename $0;

    print <<EofUSAGE;

usage: $prog [-c client_id] [-r report_email_address] [-x error_email_address] [-l client_name/pattern] [-h] [-d]
            -c - Client ID (if not specified then run for all clients)
            -r - Send summary report to this email instead of STDOUT
            -x - Send error report to this email instead of STDERR
            -l - List client ids (host pattern is optional)
            -d - display debug information to STDERR
            -v - display verbose debug information to STDERR
            -q - Do not output summary report
            -h - display this screen
EofUSAGE

    exit 1;
}

sub list_clients {
    my $host = shift;
    my $key;
    foreach $key ( sort { $a <=> $b } keys(%Common::RSDB::CLIENT_DB) ) {
        printf( "%-20s %-10s ID: %s\n", $Common::RSDB::CLIENT_DB{$key}->{db_name}, "($Common::RSDB::CLIENT_DB{$key}->{host_id})", $key )
          if ( !defined($host) || $Common::RSDB::CLIENT_DB{$key}->{db_name} =~ /$host/i );
    }
    exit 1;
}

package DB::ContractTermSource;

use lib '/app/tools/common/lib';

use lib '/app/tools/rps/lib';
use base 'RPS::DB::Item::ContractTermSource';

sub GetMapping {
    my $class = shift;
    my $dbo   = Common::RSApp::GetClientDB();
    my $sql =
"select contract_term_source_id, income_source_id from contract_term_source inner join income_source using (name) where parent_contract_term_source_id > 1";

    return $class->SUPER::GetAll($sql);
}

package RemapSource;

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

use lib '/app/tools/common/lib';
use base 'RPS::Script';

use lib '/app/tools/rps/lib';
use RPS::DB::Item::ContractTermSource;
use RPS::DB::Item::NewArtistContractTerm;

use Data::Dumper;

sub _process {
    my $self = shift;

    my $mapping = $self->_getMapping();
    my $sth     = RPS::DB::Item::NewArtistContractTerm->GetAll();

    while ( my $row = $sth->next() ) {
        if ( $row->income_source_id ) {
            assert( $mapping->{ $row->income_source_id }, "Missing mapping for income source id: " . $row->income_source_id );
            $self->debug( "Mapping income source id: "
                  . $row->income_source_id
                  . " to contract term source id: "
                  . $mapping->{ $row->income_source_id } );
            $row->contract_term_source_id( $mapping->{ $row->income_source_id } );

            $row->save();
        }
    }
}

sub _getMapping {
    my $self = shift;

    return $self->{_mapping} if ( $self->{_mapping} );

    my %result;

    my $dbo = Common::RSApp::GetCommonDB();
    my $sql =
"select contract_term_source_id, income_source_id from contract_term_source inner join income_source using (name) where parent_contract_term_source_id > 1 OR name IN ( 'MASTER', 'SYNC' )";

    my $sth = $dbo->DoCmd($sql);
    while ( my $row = $sth->fetchrow_hashref() ) {
        $result{ $row->{income_source_id} } = $row->{contract_term_source_id};
    }

    $self->{_mapping} = \%result;

    return \%result;
}

1;
