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

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

use lib '/app/tools/rps/lib';
use RPS::LabelPayee::Form;
use RPS::LabelPayee::Command::Show;

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

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

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

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 $id = $self->getParam("LabelPayeeID");

    my $form = RPS::LabelPayee::Form->new( labelPayeeID => $id );

    if ( $self->getParam('formSubmit') ) {

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

            # Get the publisherID out of the form... we may have just created a new one, after all.
            #
            $id = $form->getLabelPayeeID();

            RPS::CommandLog::Log( $self, $id );

            # on a 'regular' save, we will refresh back to the Detail page.
            # on a 'save and new', we refresh back to a blank Edit screen (with a success message).
            #

            # We want to change views, so we want to execute the Detail command now.
            #
            my $successMessage = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessFormSubmit );
            my $command;

            if (0)    # TODO -- save and new --
            {
                $command = RPS::LabelPayee::Command::Edit->new( msg => $successMessage->toString() );
            } else {
                $command = RPS::LabelPayee::Command::Show->new( msg => $successMessage->toString, LabelPayeeID => $id );
            }

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

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

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

1;

