#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::LabelRoyalty::Command::Commit;
use strict;
use warnings;
use Data::Dumper;

use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use RPS::RoyaltyRun::Status;
use RPS::LabelRoyalty::Command::List;
use RPS::Command;
use RPS::LabelRoyalty::Job::CommitLabelRoyaltyRun;
use base 'RPS::Command';

use RSApache::Response::XSLT;

sub cmd  { return 'commit'; }
sub area { return 'label_royalty'; }


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

	my $response = $self->SUPER::execute();
	return $response if $response;

    # No form here. Just sanity-check the run id, then execute the command.
    #
    my $runID = $self->getParam('LabelRoyaltyRunID');
    my $runData = RPS::DB::Item::LabelRoyaltyRun->Lookup(label_royalty_run_id => $runID);
    

    # Both success and failure go to the same page.
    # The only difference will be the message.
    #
    my $message;
    if (_commitRun($runData))
    {
        $message = RPS::Message->new(type => "success", code => Common::FormObject::kSuccessCommit);
    }
    else
    {
        $message = RPS::Message->new(type => "error", code => Common::FormObject::kErrFormSubmit);
    }
    my $command = RPS::LabelRoyalty::Command::List->new
    (
        msg => $message->toString, 
    );

    my $redirectResponse = RSApache::Response::Redirect->new($command->getRedirect());
    return $redirectResponse;
}


sub _commitRun
{
    my ($runData) = @_;
    return undef unless $runData;

    
    # Only 'complete' runs can be committed.
    #
    if (RPS::RoyaltyRun::Status::kComplete != $runData->status())
    {
        return undef;
    }

    
    # Change the run status to 'waiting to complete', then queue up the job
    #
    $runData->status(RPS::RoyaltyRun::Status::kWaitingToCommit);
    $runData->save();

    my $jobArgs = RPS::LabelRoyalty::Job::CommitLabelRoyaltyRun->new(runID => $runData->label_royalty_run_id);
    my $job = $jobArgs->enqueue();
    

    return 1;
}

1;
