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

use lib '/app/tools/rps/lib';
use RPS::Mechanical::UK::Command::List;
use RPS::Command;
use RPS::DB::Item::UKMechanicalRun;
use RPS::RoyaltyRun::Status;
use base 'RPS::Command';

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

sub cmd  { return 'invalidate'; }
sub area { return 'uk_mech'; }

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('UKMechanicalRunID');
    my $runData = RPS::DB::Item::UKMechanicalRun->Lookup( uk_mechanical_run_id => $runID );
    die "ERROR - Invalid UKMechanicalRunID $runID" unless $runData;

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

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

sub _invalidateRun {
    my ($runData) = @_;
    assert($runData);

    # We can only invalidate runs that are Completed.
    #
    my $runStatus = $runData->status();
    if ( RPS::RoyaltyRun::Status::kComplete != $runStatus ) {
        die "ERROR - UK Mechanical Run " . $runData->uk_mechanical_run_id . " is not in a 'invalidatable' state!";
    }

    # Okay, let's do it.
    #

    $runData->status(RPS::RoyaltyRun::Status::kInvalidated);
    $runData->save();

    return 1;
}

1;
