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

use lib '/app/tools/common/lib';
use Common::Assert;
use RSApache::Response::XSLT;

use lib '/app/tools/rps/lib';
use RPS::Command;
use RPS::RoyaltyRun::Status;
use base 'RPS::Command';

# !!! This is a base class;

sub _getRunData {
    my ( $self, $id ) = @_;
    assert( 0, 'override this' );
}

sub _getListCommand {
    my ( $self, $msg ) = @_;
    assert( 0, 'override this' );
}

sub _createCommitJob {
    my ( $self, $runData ) = @_;
    assert( 0, 'override this' );
}

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('MechanicalRunID');
    my $runData = $self->_getRunData($runID);

    # Both success and failure go to the same page.
    # The only difference will be the message.
    #
    my $message;
    if ( $self->_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 = $self->_getListCommand( $message->toString );

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

sub _commitRun {
    my ( $self, $runData ) = @_;
    assert($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 = $self->_createCommitJob($runData);
    my $job     = $jobArgs->enqueue();

    return 1;
}

1;
