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

use strict;
use warnings;
use Carp;
use Data::Dumper;

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

use lib '/app/tools/rps/lib';
use RPS::Statement::Artist::StatementList;
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::DB::Item::ReportQueries::ArtistReservePipeline;
use RPS::Statement::Artist::PDF;
use RPS::Statement::Artist::Excel;

use RPS::RoyaltyRun::RoyaltyRunStatusList;

use Common::FormObject;
use base 'Common::FormObject';


# !!! Convert this to a plain-ole XMLObject.
# !!! It will never appear in an editable form.


sub _init
{
    my ($self, %args) = @_;

    $self->SUPER::_init(%args);

    # !!! Shouldn't need this arg anymore.
    #
#    $self->{_payorID} = $args{payorID};
    $self->{_filterBy} = $args{filterBy};
    $self->{_page} = $args{page};


    my %properties;
    if ($args{_dbItem})
    {
        $self->_propertiesFromDBItem(\%properties, $args{_dbItem});
    }
    elsif ($args{artistRoyaltyRunID})
    {
        $self->_propertiesFromDB(\%properties, $args{artistRoyaltyRunID});
    }
    else
    {
        $self->_propertiesFromDefaults(\%properties);
    }

    $self->_initProperties(\%properties);
    $self->_initSubs(\%properties);

    return $self;
}


sub _propertiesFromDB
{
    my ($self, $hrProperties, $id) = @_;

    my $dbItem = RPS::DB::Item::ArtistRoyaltyRun->Lookup(artist_royalty_run_id => $id);
    return $self->_propertiesFromDBItem($hrProperties, $dbItem);
}


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

    $hrProperties->{artist_royalty_run_id}	= $dbItem->artist_royalty_run_id;
    $hrProperties->{ending_sale_date}		= $dbItem->ending_sale_date;
    $hrProperties->{label}					= $dbItem->label;
    $hrProperties->{start_time}				= $dbItem->start_time;
    $hrProperties->{end_time}				= $dbItem->end_time;
    $hrProperties->{status}					= $dbItem->status;
    $hrProperties->{pid}					= $dbItem->pid;
    $hrProperties->{payor_id}			    = $dbItem->payor_id;
    $hrProperties->{job_id}			        = $dbItem->job_id;
    $hrProperties->{hostname}				= $dbItem->hostname;
    $hrProperties->{created_by}				= $dbItem->created_by;
}


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

    $self->{ArtistRoyaltyRunID}	= Common::FormObject::Scalar->new(value => $props->{artist_royalty_run_id}, readOnly => 1);
    $self->{EndingSaleDate}		= Common::FormObject::Scalar::Date->new(value => $props->{ending_sale_date}, readOnly => 1);
    $self->{Label}				= Common::FormObject::Scalar::String->new(value => $props->{label}, readOnly => 1);
    $self->{StartTime}			= Common::FormObject::Scalar::DateTime->new(value => $props->{start_time}, readOnly => 1);
    $self->{EndTime}			= Common::FormObject::Scalar::DateTime->new(value => $props->{end_time}, readOnly => 1);
    $self->{Status}				= Common::FormObject::Scalar->new(value => $props->{status}, readOnly => 1);
    $self->{PID}				= Common::FormObject::Scalar->new(value => $props->{pid}, readOnly => 1);
    $self->{PayorID}		    = Common::FormObject::Scalar->new(value => $props->{payor_id}, readOnly => 1);
    $self->{JobID}		        = Common::FormObject::Scalar->new(value => $props->{job_id}, readOnly => 1);
    $self->{Hostname}			= Common::FormObject::Scalar::String->new(value => $props->{hostname}, readOnly => 1, maxlength => 64);
    $self->{CreatedBy}			= Common::FormObject::Scalar::UserName->new(value => $props->{created_by}, readOnly => 1);

	# we need to know the number of statements. we load the statement list in loadSubs,
	# but in the case when loadSubs==0, we still need that info. let's get it here, but
	# we don't want to perform this query twice, so only do it if loadSubs==0. -jff-
	#
    # JPK - This statement count code is broken and slow.
    #       It's got a bunch of baked-in logic to ignore certain types of statements, which I think 
    #       we don't need to do.  And it fetches the whole list, just to display the count...
    #
	if(!$self->loadSubs())
	{
#		my $numStatements = 0;
#		my $coll = RPS::DB::Item::ArtistRoyaltyStatement->GetByArtistRoyaltyRunID($props->{artist_royalty_run_id});
#		if($coll)
#		{
#			$numStatements = $coll->size();
#		}
#		$self->{NumberOfStatements} = Common::FormObject::Scalar::Integer->new(value => $numStatements, readOnly => 1);
        $self->{NumberOfStatements} = RPS::DB::Item::ArtistRoyaltyStatement->GetCountByArtistRoyaltyRunID($props->{artist_royalty_run_id});
	}


    # Determine whether we can download the zip file.
    # Basically, if the directory is there, and there's at least
    # 1 file in it, then they can download it.
    #
    my $canDownloadFlag;
    my $pipelineReportFlag;

    # Flags for downloading the Current Period (CP) Royalties reports
    my $canDownloadCPTextFlag;
    my $canDownloadCPExcelFlag;

    # Flags for downloading the Album Balances (AB) reports
    my $canDownloadABTextFlag;
    my $canDownloadABExcelFlag;

    # Flag for downloading Excel statement
    my $canDownloadExcelFlag;

    if ($props->{artist_royalty_run_id})
    {
        my $downloadDir = RPS::Statement::Artist::PDF::StatementPathFromRunID($props->{artist_royalty_run_id});
        #my $downloadDir = '/app/data/royalty_statements/artist/'.Common::RSApp::GetClientID().'/'.$props->{artist_royalty_run_id};
        if (-d $downloadDir)
        {
            # JPK - Over-anxious customers are downloading the files while they are still being regenerated
            # after a commit.   We need to use a semaphore instead.
            #
            if (-f "$downloadDir/COMPLETE")
            {
                $canDownloadFlag = 1;
            }

            $canDownloadCPExcelFlag = 1 if (-f "$downloadDir/EXPORT_CP_EXCEL_COMPLETE");

            $canDownloadCPTextFlag  = 1 if (-f "$downloadDir/EXPORT_CP_TEXT_COMPLETE");

            $canDownloadABExcelFlag = 1 if (-f "$downloadDir/EXPORT_AB_EXCEL_COMPLETE");

            $canDownloadABTextFlag  = 1 if (-f "$downloadDir/EXPORT_AB_TEXT_COMPLETE");

            $canDownloadExcelFlag = 1 if (-f "$downloadDir/EXCEL_COMPLETE");
#            # Files in here?
#            #
#            if (opendir(DIR, $downloadDir))
#            {
#                my @files;
#                my @pdfFiles = grep { /\.pdf/ } readdir(DIR);
#                if (scalar @pdfFiles > 0)
#                {
#                    $canDownloadFlag = 1;
#                }
#
#                closedir(DIR);
#            }
        }
        $pipelineReportFlag = RPS::DB::Item::ReportQueries::ArtistReservePipeline->ReportAvailable($props->{artist_royalty_run_id});
    }

    $self->{CanDownload} = $canDownloadFlag;
    $self->{PipelineReportAvailable} = $pipelineReportFlag;

	$self->{RoyaltyRunStatus} = RPS::RoyaltyRun::RoyaltyRunStatusList->new( artist => 1, payorID => $self->PayorID );

    $self->{CanDownloadCPExcel} = $canDownloadCPExcelFlag;
    $self->{CanDownloadCPText} = $canDownloadCPTextFlag;

    $self->{CanDownloadABExcel} = $canDownloadABExcelFlag;
    $self->{CanDownloadABText} = $canDownloadABTextFlag;

    $self->{CanDownloadExcel} = $canDownloadExcelFlag;

}



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

	if($self->loadSubs())
	{
        # Load the list of statement lines.
        #
        $self->{ArtistRoyaltyStatementList} = RPS::Statement::Artist::StatementList->new
        (
            artistRoyaltyRunID => $props->{artist_royalty_run_id},
            payorID => $self->PayorID(),
            filterBy => $self->{_filterBy},
            page => $self->{_page},
        );
	}

    return $self;
}


sub _propertiesFromDefaults
{
    my ($self, $hrProperties) = @_;
}



###
1;#
###
