package RPS::Report::Dynamic::Payee::Publishers::US;

use strict;
use warnings;

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

use Common::Client;
use base 'RPS::Report::Dynamic::Payee::Publishers';
use RPS::DB::Item::DynamicReport::Payee::Publishers::US;
use RPS::DB::Item::TrackLicense;
use RPS::DB::Item::PublisherAccount;
use RPS::DB::Item::PublisherIndirectBalanceAccount;

sub Type { 'US Publishers' }
sub ClientTypeMask { return Common::Client::kUSMechanicals; }


sub _getCollection {
    my $self = shift;

    my $dateType;
    my $dateTypeParam = $self->parameters()->{Criteria}->DateType();
    if ($dateTypeParam)
    {
        if ('Date Created' eq $dateTypeParam)
        {
            $dateType = 'date_created';
        }
        elsif('Date Modified' eq $dateTypeParam)
        {
            $dateType = 'date_modified';
        }
    }
   
    return RPS::DB::Item::DynamicReport::Payee::Publishers::US->ReportQuery(
        dateType => $dateType,
        startDate => $self->parameters()->{Criteria}->StartDate(),
        endDate => $self->parameters()->{Criteria}->EndDate(),
#        showProcessed => $self->_showProcessed(),
#        showUnprocessed => $self->_showUnprocessed(),
    );
}


#sub _getDirectAccounts
#{
#    my ($self, $pubID) = @_;
#    return RPS::DB::Item::PublisherAccount->GetByPublisherID($pubID);
#}
#
#sub _getIndirectAccounts
#{
#    my ($self, $pubID) = @_;
#    return RPS::DB::Item::PublisherIndirectBalanceAccount->GetByPublisherID($pubID);
#}
#
#
# It's going to be expensive to add a sub-query to each row to get the number of licenses for each publisher.
# I'm going to do that query out-of-band and cache the results.
#
my $gNumLicensesCache;
sub _numLicenses
{
    my ($self, %args) = @_;
    my $rowItem = $args{row};
    my $fieldName = $args{field};

    my $id = $rowItem->$fieldName();

    my $num;
    if ($id)
    {
        if (! $gNumLicensesCache)
        {
            $gNumLicensesCache = {};
            my $counts = RPS::DB::Item::TrackLicense->GetCountsForAllPublishers();
            foreach my $data (@$counts)
            {
                $gNumLicensesCache->{ $data->{publisher_id} } = $data->{count};
            }
        }

        $num = $gNumLicensesCache->{$id};
    }

    return $num;
}



1;
