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

use lib '/app/tools/rps/lib';
use RPS::Product::Command::Edit;
use RPS::Catalog::Command::Show;
use RPS::Product::Product;
use RPS::DB::Item::Product;
use RPS::DB::Item::Track;

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

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

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

use constant kTemplate => "/app/tools/rps/templates/product/index.xsl";

sub execute {
    my ($self) = @_;

    my $response = $self->SUPER::execute();
    return $response if $response;

    my $productID = $self->getParam('ProductID') || 0;
    my $aChildProductIDs = $self->_getChildProducts($productID);
    my $oProduct;

    unless ( $oProduct = RPS::Product::Product->new( productID => $productID ) ) {
        my $command = RPS::Catalog::Command::Search->new();
        return RSApache::Response::Redirect->new( $command->getRedirect() );
    }

    if ( $self->_isAllowedToDelete($productID, $aChildProductIDs) && $oProduct->delete() ) {

        # Redirect to the Show command.
        # We'll have to get the correct album_id.
        #
        my $albumID = $oProduct->AssetID();
        if ( RPS::DB::Item::Product::kProductTypeDigitalTrack == $oProduct->ProductTypeID ) {
            my $oTrackData = RPS::DB::Item::Track->Lookup( track_id => $albumID );
            $albumID = $oTrackData->album_id;
        }

        my $successMessage = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessFormSubmit );
        my %showParams = (
            AlbumID => $albumID,
            msg     => $successMessage->toString(),
        );
        my $command = RPS::Catalog::Command::Show->new(%showParams);
        return RSApache::Response::Redirect->new( $command->getRedirect() );
    }
    else {
        my $errorMsg = RPS::Message->new( type => "error", code => Common::FormObject::kErrDelete );
        my %showParams = (
            ProductID => $productID,
            msg       => $errorMsg->toString(),
        );
        my $command = RPS::Product::Command::Edit->new(%showParams);
        return RSApache::Response::Redirect->new( $command->getRedirect() );
    }

    $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );

    return $response;
}

sub _isAllowedToDelete {
    my ($self, $productID, $aChildProductIDs) = @_;

    # If there are any "open" (completed, running, waiting to run) mechanical runs, we don't want to allow any changes.
    my $openMcpsRuns = 0;
    my $openUSRuns   = 0;
    my $openCARuns   = 0;
    my $mcpsLicense;

    if ($productID) {
        $openUSRuns = RPS::DB::Item::MechanicalRun->GetOpenRunCountForProduct( $productID, @$aChildProductIDs );
        $openCARuns = RPS::DB::Item::CAMechanicalRun->GetOpenRunCountForProduct( $productID, @$aChildProductIDs);
        if ( $mcpsLicense = RPS::DB::Item::McpsLicense->Lookup( product_id => $productID ) ) {
            $openMcpsRuns = RPS::DB::Item::UKMechanicalRun->GetOpenRunCount( $mcpsLicense->payor_id );
        }
    }

    my $canBeDeleted =
           !$openMcpsRuns && !$openCARuns && !$openUSRuns && !$mcpsLicense
        && RPS::DB::Item::Product->CanDelete( $productID, @$aChildProductIDs )
        && !RPS::DB::Item::LicenseReserve->CountRemainingPeriodsByProductID( $productID, @$aChildProductIDs )
        && !RPS::DB::Item::CALicenseReserve->CountRemainingPeriodsByProductID( $productID, @$aChildProductIDs )
        && !RPS::DB::Item::ArtistContractTermReserve->CountRemainingPeriodsByProductID( $productID, @$aChildProductIDs );

    return $canBeDeleted;
}

sub _getChildProducts {
    my ($self, $productID) = @_;

    return RPS::DB::Item::Product->GetChildProductsByProductID($productID);
}


1;
