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

use Sys::Hostname;

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

use lib '/app/tools/rps/lib';
use RPS::DB::Item::UKMechanicalRun;
use RPS::Statement::UKMechanical::StatementList;
use RPS::Payor::PayorList;
use RPS::Mechanical::UK::Job::RunMechanicals;
use RPS::RoyaltyRun::RoyaltyRunStatusList;
use RPS::RoyaltyRun::Status;

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->new();

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

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

    return $self;
}


sub validate
{
    my $self = shift;

    return 0 if( $self->HasRunError() );

    $self->{RoyaltyRunStatus} = RPS::RoyaltyRun::RoyaltyRunStatusList->new(
                                    ukMechanical => 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::UKMechanicalRun->Create
    (
        ending_sale_date => $self->EndingSaleDate(),
        quarter => $self->Quarter(),
        year => $self->Year(),
        payor_id => $self->PayorID(),
        status => RPS::RoyaltyRun::Status::kWaitingToRun,
    );

    $newRun->save();


    # Create the new job, and put it in the queue.
    #
    my $jobArgs = RPS::Mechanical::UK::Job::RunMechanicals->new
    (
        runID => $newRun->uk_mechanical_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;#
###
