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

use lib '/app/tools/common/lib';

use lib '/app/tools/rps/lib';
use RPS::RoyaltyRun::Status;
use RPS::LabelRoyalty::Command::List;
use RPS::Command;
use RPS::LabelRoyalty::Job::DeleteLabelRoyaltyRun;
use RPS::DB::Item::LabelRoyaltyRun;
use base 'RPS::Command';

use RSApache::Response::XSLT;

sub cmd  { return 'delete'; }
sub area { return 'label_royalty'; }

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('LabelRoyaltyRunID');
    my $runData = RPS::DB::Item::LabelRoyaltyRun->Lookup( label_royalty_run_id => $runID );

    # 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::LabelRoyalty::Command::List->new( msg => $message->toString, );

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

sub _deleteRun {
    my ($runData) = @_;
    return undef unless $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 - 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 = RPS::LabelRoyalty::Job::DeleteLabelRoyaltyRun->new( runID => $runData->label_royalty_run_id );
    my $job = $jobArgs->enqueue();

    return 1;
}

1;
