#------------------------------------------------------------
# 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::UKMechanicalRun;
use RPS::DB::Item::McpsLicense;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::CAMechanicalRun;

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");
    my $productID = $self->getParam("ProductID");
    if (! $productID)
    {
        $productID = $self->getParam("Form_Product_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;    
    
    if ($productID)
    {
        $openUSRuns = RPS::DB::Item::MechanicalRun->GetOpenRunCountForProduct($productID);
	    $openCARuns = RPS::DB::Item::CAMechanicalRun->GetOpenRunCountForProduct($productID);
           
        my $mcpsLicense = RPS::DB::Item::McpsLicense->Lookup(product_id => $productID);
        
        if ($mcpsLicense) 
        {
    
            my $payorID = $mcpsLicense->payor_id();
            $openMcpsRuns = RPS::DB::Item::UKMechanicalRun->GetOpenRunCount($payorID);
	            
        }
    }

    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;	
	
    $response = RSApache::Response::XSLT->new($self->{xml}, kTemplate);
    return $response;
}


1;
