#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::Catalog::Command::Edit;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::RSApp;
use Common::Client;

use lib '/app/tools/metadata/lib';
use Metadata::Validate::Harness;

use lib '/app/tools/rps/lib';
use Common::FormObject;
use Common::Log;
use RPS::Catalog::EditForm;
use RPS::Catalog::DAAlbumForm;
use RPS::Catalog::Command::Show;
use RPS::Command;
use RPS::CommandLog;
use RPS::Message;

use base 'RPS::Command';

use RSApache::Response::XML;
use RSApache::Response::XSLT;
use RSApache::Response::Redirect;

sub cmd  { return 'edit'; }
sub area { return 'catalog'; }

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

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

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

	my $albumID = $self->getParam('AlbumID');

    my $form;

    # We want to use different forms depending on what sort of client we are...
    #
    my $client = Common::Client::Current();
    if ($client->isClientType(Common::Client::kArtist) ||
        $client->isClientType(Common::Client::kUSMechanicals) ||
        $client->isClientType(Common::Client::kUKMechanicals)
       )
    {
        $form = RPS::Catalog::EditForm->new(albumID => $albumID);
    }
    else
    {
        $form = RPS::Catalog::DAAlbumForm->new(albumID => $albumID);
    }


	if ($self->getParam('formSubmit'))
	{
		my $validator = new Metadata::Validate::Harness( failState => Validate::kStatusDuplicate );
		if ($form->assignCGIParams('Form', $self->getParams()) && $form->validate( metadataValidator => $validator ))
		{
			$form->save();

            # Update was successful, log it.
            #
            RPS::CommandLog::Log($self, $albumID);


			# We want to change views, so we want to redirect to the Show command now.
			#
			my $successMessage = RPS::Message->new(type => "success", code => Common::FormObject::kSuccessFormSubmit);
			my %showParams = (
				AlbumID => $form->albumID(),
				msg => $successMessage->toString(),
			);
			my $command = RPS::Catalog::Command::Show->new(%showParams);
			return RSApache::Response::Redirect->new($command->getRedirect());
		}
		else
		{
            # 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 );
            }
            
			$form->setError(Common::FormObject::kErrFormSubmit);
			$self->addMessageXML(type => "error", code => Common::FormObject::kErrFormSubmit);
		}
	}

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

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

	return $response;
}



1;
