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

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

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

sub cmd  { return 'delete'; }
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 (_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 = RPS::Mechanical::UK::Command::List->new
    (
        msg => $message->toString, 
    );

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


sub _deleteRun
{
    my ($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)
    {
        die "ERROR - UK Mechanical Run " . $runData->uk_mechanical_run_id . " is not in a 'deletable' state!";
    }

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

    my $jobArgs = RPS::Mechanical::UK::Job::DeleteRun->new(runID => $runData->uk_mechanical_run_id);
    my $job = $jobArgs->enqueue();
    
    # Might as well remove the entries in the Retention report table for this run too.
    #
    RPS::DB::Item::ReportQueries::UKMechRetentionRunSummary->Delete($runData->uk_mechanical_run_id);

    return 1;
}

1;
