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

use lib '/app/tools/rps/lib';
use RPS::Catalog::AdvanceForm;
use RPS::ArtistContract::Command::Show;
use RPS::ArtistContract::Command::Search;

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

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

sub cmd  { return 'advance'; }
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 $albumContractID = $self->getParam('AlbumContractID');
    my $advanceID       = $self->getParam('AdvanceID');
    my $form;

    if ($albumContractID) {
        $form = RPS::Catalog::AdvanceForm->new( albumContractID => $albumContractID );
    } elsif ($advanceID) {
        $form = RPS::Catalog::AdvanceForm->new( albumContractAdvanceID => $advanceID );
    } else {
        my $command = RPS::ArtistContract::Command::Search->new();
        return RSApache::Response::Redirect->new( $command->getRedirect() );
    }

    if ( $self->getParam('formSubmit') ) {
        if ( $form->assignCGIParams( 'Form', $self->getParams() ) && $form->validate() ) {
            $form->save();

            my $command;

            # Redirect to the Show command.
            #
            my $successMessage = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessFormSubmit );
            my %showParams = (
                ContractID => $form->contractID(),
                msg        => $successMessage->toString(),
            );
            $command = RPS::ArtistContract::Command::Show->new(%showParams);
            return RSApache::Response::Redirect->new( $command->getRedirect() );
        } else {
            $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;
