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

use lib '/app/tools/rps/lib';

use RPS::Command;
use base 'RPS::Command';

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

sub cmd  { return 'invalidate'; }


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);
    
    die "ERROR - Invalid MechanicalRunID $runID" unless $runData;


    # Both success and failure go to the same page.
    # The only difference will be the message.
    #
    my $message;
    if (_invalidateRun($self, $runData))
    {
        $message = RPS::Message->new(type => "success", code => Common::FormObject::kSuccessInvalidate);
    }
    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 _invalidateRun
{
    my ($self, $runData) = @_;
    assert($runData);
    
    # We can only invalidate runs that are Completed.
    # 
    my $runID = $self->_runID();
    my $runStatus = $runData->status();
    if ($self->_completeStatus() != $runStatus)
    {
        die "ERROR - Mechanical Run " . $runData->$runID . " is not in a 'invalidatable' state!";
    }

    # Okay, let's do it.
    #
    
    $runData->status($self->_invalidStatus());
    $runData->save();
    
    return 1;
}

1;
