#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::Mechanical::US::MechanicalRun;

use Carp;

use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::Util;

use lib '/app/tools/rps/lib';
use RPS::Statement::Mechanical::US::StatementList;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::MechanicalRunUnlicensedTrackLog;
use RPS::Statement::Mechanical::US::Text;
use RPS::RoyaltyRun::RoyaltyRunStatusList;
use RPS::DB::Item::ReportQueries::MechanicalReservePipeline;

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

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

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

    # !!! This can probably go away soon.
    #
    $self->{_payorID}  = $args{payorID};
    $self->{_filterBy} = $args{filterBy};
    $self->{_page}     = $args{page};
    $self->{_pageSize} = $args{pageSize};

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

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

    return $self;
}

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

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

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

    $hrProperties->{mechanical_run_id} = $dbItem->mechanical_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->{MechanicalRunID} = Common::FormObject::Scalar->new( value => $props->{mechanical_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 );

    # !!! At some point, 'Label' will be able to be defined when the run is started.
    # !!! For now, we'll just construct it.
    #
    #my $label = $self->{StartDate}->formatMDY() . " - " . $self->{EndDate}->formatMDY();
    #$self->{Label} = Common::FormObject::Scalar::String->new(value => $label, readOnly => 1);

    my $count = RPS::DB::Item::MechanicalStatement->GetActiveCountByMechanicalRunID( $props->{mechanical_run_id} );
    $self->{NumStatements} = $count;

    # 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 $canDownloadPDF;
    my $canDownloadText;
    my $canDownloadExportText;
    my $canDownloadExportExcel;
    my $accrualReportFlag;
    my $pipelineReportFlag;
    # Flag for distributing statements through Payee Portal
    my $canDistribute;

    if ( $props->{mechanical_run_id} ) {
        my $downloadDir = RPS::Statement::Mechanical::US::Text->StatementPathFromRunID( $props->{mechanical_run_id} );

        #my $downloadDir = '/app/data/royalty_statements/mechanical/'.Common::RSApp::GetClientID().'/'.$props->{mechanical_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" ) {
                $canDownloadPDF = 1;
            }
            if ( -f "$downloadDir/TEXT_COMPLETE" ) {
                $canDownloadText = 1;
            }
            if ( -f "$downloadDir/EXPORT_TEXT_COMPLETE" ) {
                $canDownloadExportText = 1;
            }
            if ( -f "$downloadDir/EXPORT_EXCEL_COMPLETE" ) {
                $canDownloadExportExcel = 1;
            }
        }

        $accrualReportFlag = RPS::DB::Item::MechanicalRunUnlicensedTrackLog->ReportAvailable( $props->{mechanical_run_id} );
        $pipelineReportFlag = RPS::DB::Item::ReportQueries::MechanicalReservePipeline->ReportAvailable( $props->{mechanical_run_id} );
    }

    if ( $props->{status} == RPS::RoyaltyRun::Status::kCommitted || $props->{status} == RPS::RoyaltyRun::Status::kClosed ) {
        $canDistribute = 1;
    }

    $self->{CanDistribute}           = $canDistribute;
    $self->{CanDownload}             = $canDownloadPDF;
    $self->{CanDownloadText}         = $canDownloadText;
    $self->{AccrualReportAvailable}  = $accrualReportFlag;
    $self->{PipelineReportAvailable} = $pipelineReportFlag;
    $self->{CanDownloadExportText}   = $canDownloadExportText;
    $self->{CanDownloadExportExcel}  = $canDownloadExportExcel;

    # Determine whether we can download the excel file.
    # Basically, if the directory is there, and there's an excel file in there
    # then they can download it.
    #
    my $canDownloadExcelFlag;

    if ( $props->{mechanical_run_id} ) {
        my $downloadDir = '/app/data/royalty_statements/mechanical/' . Common::RSApp::GetClientID() . '/' . $props->{mechanical_run_id};
        if ( -d $downloadDir ) {

            # Files in here?
            #
            if ( opendir( DIR, $downloadDir ) ) {
                my @files;
                my @excelFiles = grep { /\.xls/ } readdir(DIR);
                if ( scalar @excelFiles > 0 ) {
                    $canDownloadExcelFlag = 1;
                }

                closedir(DIR);
            }
        }
    }

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

}

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

    if ( $self->loadSubs() ) {

        # Load the list of statement lines.
        #
        $self->{MechanicalStatementList} = RPS::Statement::Mechanical::US::StatementList->new(
            mechanicalRunID => $props->{mechanical_run_id},
            payorID         => $self->{_payorID},
            filterBy        => $self->{_filterBy},
            page            => $self->{_page},
            pageSize        => $self->{_pageSize},
        );
    }

    return $self;
}

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

sub GenerateFileLabel {
    my ($label) = @_;

    my $fileLabel = Common::Util::clean_name($label);

    return $fileLabel;
}

###
1;    #
###
