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

use Sys::Hostname;

use lib '/app/tools/common/lib';
use Common::FormObject;
use Common::RSApp;

use lib '/app/tools/raptor/lib';
use Raptor::DB::Item::Period;

use lib '/app/tools/rps/lib';
use RPS::RoyaltyRun::Status;
use RPS::DB::Item::LabelRoyaltyRun;
use RPS::LabelRoyalty::LabelRoyaltyRun;
use RPS::Payor::PayorList::WithCommitDate;
use RPS::RoyaltyRun::RoyaltyRunStatusList;

use RPS::LabelRoyalty::Job::RunLabelRoyalties;

use base 'Common::FormObject';

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

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

    # I want:
    # A list of payors
    # a place to enter the start date
    # a place to enter the end date
    # ? A way to set the debugging level ?
    #
    $self->{PayorList} = RPS::Payor::PayorList::WithCommitDate->new( runType => RPS::DB::Item::SaleRunMap::kRunTypeLabelRoyalty );

    $self->{PayorID}        = Common::FormObject::Scalar->new( required => 1 );
    $self->{EndingSaleDate} = Common::FormObject::Scalar::Date->new();
    $self->{Label}          = Common::FormObject::Scalar::String->new( required => 1 );
    $self->{LogLevel}       = Common::FormObject::Scalar->new( value => 2, required => 1 );

    $runStatus = RPS::RoyaltyRun::RoyaltyRunStatusList->new( label => 1 )->LabelRuns();
    $self->{HasRunError} = $runStatus->Error();

    # We need the date that the last period was closed.
    my $periodDate = Raptor::DB::Item::Period->GetLatestPeriodDate();
    $self->{PeriodCloseDate} = Common::FormObject::Scalar::Date->new( value => $periodDate );

    return $self;
}

sub validate {
    my $self = shift;

    return 0 if ( $self->HasRunError );

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

    return 0 unless ( $self->{RoyaltyRunStatus}->CanEdit() );

    return $self->SUPER::validate();
}

sub save {
    my ($self) = @_;

    # First, create the run entry.
    #
    my $newRun = RPS::DB::Item::LabelRoyaltyRun->Create(
        label            => $self->Label(),
        ending_sale_date => $self->EndingSaleDate(),
        payor_id         => $self->PayorID(),
        status           => RPS::RoyaltyRun::Status::kWaitingToRun,
    );

    $newRun->save();

    # Create the new job.
    #
    my $jobArgs = RPS::LabelRoyalty::Job::RunLabelRoyalties->new( runID => $newRun->label_royalty_run_id, logLevel => $self->LogLevel() );
    my $job = $jobArgs->enqueue();

    # Stash the job id in the run table.
    #
    $newRun->job_id( $job->id() );
    $newRun->save();
}

###
1;    #
###
