#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Mechanical::Command::Delete;
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';


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

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

sub _createDeleteJob
{
    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->_getRunDBItem($runID);
    

    # Both success and failure go to the same page.
    # The only difference will be the message.
    #
    my $message;
    if ($self->_deleteRun($runData))
    {
        $message = RPS::Message->new(type => "success", code => Common::FormObject::kSuccessDelete);
    }
    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 _deleteRun
{
    my ($self, $runData) = @_;
    assert($runData);
    
    # So, we can delete runs in a variety of states.
    # For now, I don't want to delete runs that are in flux - so, if it is
    # running, or in a 'waiting' state, you are out of luck.
    # And, I don't want to delete committed or closed runs either.
    # 
    my $runStatus = $runData->status();
    if (RPS::RoyaltyRun::Status::kComplete != $runStatus
     && RPS::RoyaltyRun::Status::kAborted != $runStatus
     && RPS::RoyaltyRun::Status::kInvalidated != $runStatus)
    {
        # !!! Not going to go out gracefully - We should never even _try_ to delete
        # runs in the wrong state.
        #
        die "ERROR - incorrect status - cannot delete";
    }

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

    my $jobArgs = $self->_createDeleteJob($runData);
    my $job = $jobArgs->enqueue();

    return 1;
}

1;
