#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::License::CA::TrackLicense;

use strict;
use warnings;
use Data::Dumper;
use Carp;
use Date::Calc qw( Date_to_Days Decode_Date_US );

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Util qw(decodeDateMysql);
use Common::Log;

use lib '/app/tools/rps/lib';
use RPS::License::BaseTrackLicense;
use RPS::License::LicenseType;
use RPS::Publisher::CA::Publisher;
use RPS::DB::Item::CATrackLicense;
use RPS::DB::Item::CALicenseReserve;
use RPS::DB::Item::FinanceTransaction;
use RPS::DB::Item::ReserveLiquidation;
use RPS::DB::Item::CAMechanicalStatementItem;
use RPS::DB::Item::CAMechanicalStatementLicense;
use RPS::DB::Item::CAPublisherTrackCrossedLicenseAccount;
use RPS::License::ReserveLiquidationList;
use RPS::DB::Item::PendingTransaction;

use RPS::License::CA;
use base 'RPS::License::BaseTrackLicense';

sub _getDBItem {
    my ( $self, $id ) = @_;
    return RPS::License::CA::GetDBItem($id);
}

sub _type { return RPS::License::LicenseType::kPublishingLicense; }

sub _propertiesFromDBItem {
    my ( $self, $hrProperties, $dbItem ) = @_;

    $self->SUPER::_propertiesFromDBItem( $hrProperties, $dbItem );
    $hrProperties->{ca_track_license_id} = $dbItem->ca_track_license_id,
      $hrProperties->{ca_publisher_id}   = $dbItem->ca_publisher_id,
      $hrProperties->{issuer_song_id}    = $dbItem->issuer_song_id,
      ;
}

sub _initProperties {
    my ( $self, $props ) = @_;

    $self->SUPER::_initProperties($props);

    $self->{TrackLicenseID} = Common::FormObject::Scalar->new( value => $props->{ca_track_license_id}, readOnly => 1 );
    $self->{PublisherID}    = Common::FormObject::Scalar->new( value => $props->{ca_publisher_id} );
    $self->{IssuerSongID}   = Common::FormObject::Scalar->new( value => $props->{issuer_song_id}, maxlength => 40 );

    $self->createPublisher();

    if ( $props->{ca_track_license_id} ) {

        # We need to mark the license so that we can tell if it's ever been used in a run (that wasn't deleted).
        #
        my $inUse = 0;

        my $licenseCount = RPS::DB::Item::CAMechanicalStatementLicense->LicenseCount( $props->{ca_track_license_id} );
        if ( $licenseCount > 0 ) {
            $inUse = 1;
        }

        # Let's also check for (historical) reserves, just to be safe

        if ( $inUse == 0 ) {
            my $reserveCount = RPS::DB::Item::CALicenseReserve->CountByTrackLicenseID( $props->{ca_track_license_id} );
            if ( $reserveCount > 0 ) {
                $inUse = 1;
            }
        }

        # And lastly let's check for committed (that is, non-pending) transactions.
        my $trackLicense = RPS::DB::Item::CATrackLicense->Lookup( ca_track_license_id => $props->{ca_track_license_id} );
        if ( $inUse == 0 ) {
            if ( $trackLicense->finance_account_id ) {
                my $transactions =
                  RPS::DB::Item::FinanceTransaction->GetAccountTransactions( finance_account_id => $trackLicense->finance_account_id );
                while ( $transactions->hasNext() ) {
                    $inUse = 1;
                    last;
                }
            }
        }

        # Additionally,  we have to heck for pending transactions
        $self->{HasPendingTransaction} = 0;
        if ( $trackLicense->finance_account_id ) {
            my $pendingTransactions = RPS::DB::Item::PendingTransaction->Lookup( finance_account_id => $trackLicense->finance_account_id );
            $self->{HasPendingTransaction} = 1 if $pendingTransactions;
        }

        $self->{InUse} = $inUse;

    }

}

sub _setDBValues {
    my ( $self, $dbItem ) = @_;
    assert($dbItem);
    $self->SUPER::_setDBValues($dbItem);

    $dbItem->ca_publisher_id( $self->PublisherID() );
    $dbItem->issuer_song_id( $self->IssuerSongID() );
}

sub _getCountryCodeMapForValidation {
    my ($self) = @_;
    my $matchingProductTypes = $self->_getMatchingProductTypes( $self->ProductTypeID );

    my %countryCodeMap;
    my $similarLicenses =
      RPS::DB::Item::CATrackLicense->GetByTrackPublisherProductTypeAndDate( $self->TrackID(), $self->PublisherID,
        $self->PayorID, $matchingProductTypes, $self->TermStart, $self->TermEnd );
    while ( my $similarLicense = $similarLicenses->next() ) {

        # Skip over _this_ track license...
        #
        next if ( $self->TrackLicenseID() && $similarLicense->ca_track_license_id == $self->TrackLicenseID() );

        # Skip all inactive licenses
        #
        next if ( $similarLicense->inactive );

        # Skip unless there is an overlap of start and end terms
        #
        next unless ( $similarLicense->{start_term_overlap} || $similarLicense->{end_term_overlap} );
        my $ccMapItems = RPS::DB::Item::RegionCountryMap->GetByRegionID( $similarLicense->region_id() );
        while ( my $mapItem = $ccMapItems->next() ) {
            $countryCodeMap{ $mapItem->country_code } = 1;
        }
    }

    return \%countryCodeMap;
}

sub _getPublisherObject {
    my ( $self, $publisherID ) = @_;
    assert($publisherID);

    my $pubObj = RPS::Publisher::CA::Publisher->new( publisherID => $publisherID, readOnly => 1 );

    return $pubObj;
}

sub createPublisher {
    my $self = shift;

    $self->{Publisher} = $self->_getPublisherObject( $self->PublisherID )
      if ( $self->PublisherID );
}

###
1;    #
###
