#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Product::Command::Edit;

use Data::Dumper;

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

use lib '/app/tools/rps/lib';
use RPS::Message;
use RPS::Product::EntryForm;
use RPS::Product::Command::Show;
use RPS::DB::Item::Product;
use RPS::DB::Item::UKMechanicalRun;
use RPS::DB::Item::McpsLicense;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::CAMechanicalRun;
use RPS::DB::Item::LicenseReserve;
use RPS::DB::Item::CALicenseReserve;
use RPS::DB::Item::ArtistContractTermReserve;

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

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

sub cmd  { return "edit"; }
sub area { return "product"; }

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

    # Give any inherited methods the first crack at this.
    # (This checks for login and basic access permissions).
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $albumID   = $self->getParam("AlbumID")   || 0;
    my $productID = $self->getParam("ProductID") || $self->getParam("Form_Product_ProductID") || 0;
    my $aChildProductIDs = $self->_getChildProducts($productID);

    my $form = RPS::Product::EntryForm->new( albumID => $albumID, productID => $productID );

    # $self->{xml}{Form} = $form;

    # Do a little prevalidation to show errors
    if ( $self->getParam('show_errors') ) {
        my $harness = new Metadata::Validate::Harness( failState => Validate::kStatusOK, ignoreCurrentData => 1 );
        $form->validate( metadataValidator => $harness );
    }

    # 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 );
        }
    }

    if ( $self->getParam('formSubmit') && $openMcpsRuns == 0 && $openUSRuns == 0 && $openCARuns == 0 ) {

        # Apply cgi parameters, then save changes if all went well.
        #
        if ( $form->assignCGIParams( 'Form', $self->getParams() ) && $form->validate() ) {
            $form->save();

            RPS::CommandLog::Log( $self, $form->productID() );

            # Upon success we redirect back to the Catalog Show command.
            #
            my $successMessage = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessFormSubmit );
            my %showParams = (
                ProductID => $form->productID(),
                msg       => $successMessage->toString(),
            );
            my $command = RPS::Product::Command::Show->new(%showParams);

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

            # We stay on the same page, and display our errors.
            #
            $form->setError(Common::FormObject::kErrFormSubmit);
            $self->addMessageXML( type => "error", code => Common::FormObject::kErrFormSubmit );
        }
    }

    my $template = kTemplate;

    # JPK - This is a hack for development purposes...
    #
    if ( $self->getParam('hack') ) {
        $template = '/app/tools/rps/templates/product/index_hack.xsl';
    }

    $self->{xml}{Form}                        = $form;
    $self->{xml}{Form}{OpenMcpsRuns}          = $openMcpsRuns;
    $self->{xml}{Form}{OpenCARuns}            = $openCARuns;
    $self->{xml}{Form}{OpenUSRuns}            = $openUSRuns;

    $productID //= 0;
    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 );

    $self->{xml}{Form}{Product}{CanBeDeleted} = $canBeDeleted;

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

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

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


1;
