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

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

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

use lib '/app/tools/rps/lib';
use RPS::Statement::UKMechanical::StatementList;
use RPS::DB::Item::UKMechanicalRun;
use RPS::DB::Item::Payor;
use RPS::Statement::UKMechanical::McpsText;
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);

    $self->{_filterBy} = $args{filterBy};

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

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

    return $self;
}


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

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


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

    $hrProperties->{uk_mechanical_run_id}	= $dbItem->uk_mechanical_run_id;
    $hrProperties->{ending_sale_date}		= $dbItem->ending_sale_date;
    $hrProperties->{quarter}                = $dbItem->quarter;
    $hrProperties->{year}                   = $dbItem->year;
    $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->{UKMechanicalRunID}	= Common::FormObject::Scalar->new(value => $props->{uk_mechanical_run_id}, readOnly => 1);
    $self->{EndingSaleDate}		= Common::FormObject::Scalar::Date->new(value => $props->{ending_sale_date}, readOnly => 1);
    $self->{Quarter}            = Common::FormObject::Scalar->new(value => $props->{quarter}, readOnly => 1);
    $self->{Year}               = Common::FormObject::Scalar->new(value => $props->{year}, 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-
	#
	if(!$self->loadSubs())
	{
		my $numStatements = 0;
		my $coll = RPS::DB::Item::McpsStatement->GetByRunID($props->{uk_mechanical_run_id});
		if($coll)
		{
			$numStatements = $coll->size();
		}
		$self->{NumberOfStatements} = Common::FormObject::Scalar::Integer->new(value => $numStatements, readOnly => 1);
	}


    # 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;

    if ($props->{uk_mechanical_run_id})
    {
        my $downloadDir = RPS::Statement::UKMechanical::McpsText::StatementPathFromRunID($props->{uk_mechanical_run_id});
        #my $downloadDir = '/app/data/royalty_statements/uk_mechanical/'.Common::RSApp::GetClientID().'/'.$props->{uk_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;
            }

            # There's only one text file, so we can keep this test.
            #
            if (opendir(DIR, $downloadDir))
            {
                my @textFiles = grep { /\.txt/ } readdir(DIR);
                if (scalar @textFiles > 0)
                {
                    $canDownloadText = 1;
                }

                closedir(DIR);
            }
        }

    }

    $self->{CanDownloadPDF} = $canDownloadPDF;
    $self->{CanDownloadText} = $canDownloadText;
	$self->{RoyaltyRunStatus} = RPS::RoyaltyRun::RoyaltyRunStatusList->new( ukMechanical => 1, payorID => $self->PayorID );


}



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

	if($self->loadSubs())
	{
        # Load the list of statement lines.
        #
        $self->{McpsStatementList} = RPS::Statement::UKMechanical::StatementList->new
        (
            ukMechanicalRunID => $props->{uk_mechanical_run_id},
            payorID => $self->PayorID(),
            filterBy => $self->{_filterBy},
        );
	}

    return $self;
}


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


sub GenerateFileLabel
{
    my ($run) = @_;
    my $fileLabel;

    my $payor = RPS::DB::Item::Payor->Lookup(payor_id => $run->payor_id());
    my $payorName = $payor->name();
    $payorName =~ s/\W//g;

    $fileLabel = $payorName . "Q" . $run->quarter . $run->year;

    return $fileLabel;
}

sub _parseDate
{
    my ($date) = @_;

    my ($y, $m, $d) = split('-', $date);

    # Truncate year to 2 characters, if necessary
    #
    $y = substr($y, -2);

    return ($y, $m, $d);
}


###
1;#
###
