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

use lib '/app/tools/rps/lib';
use RPS::XMLObject;
use RPS::Contract::EditForm;
use RPS::Contract::Command::Show;

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

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

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

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

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

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

    my $id = $self->getParam('ContractID');
    my $form = RPS::Contract::EditForm->new( contractID => $id );

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

            # We want to change views, so we want to redirect to the Show command now.
            #
            my $successMessage = RPS::Message->new( type => "success", code => RPS::XMLObject::kSuccessFormSubmit );
            my %showParams = (
                ContractID => $form->contractID(),
                msg        => $successMessage->toString(),
            );
            my $command = RPS::Contract::Command::Show->new(%showParams);
            return RSApache::Response::Redirect->new( $command->getRedirect() );
        } else {
            $form->setError(RPS::XMLObject::kErrFormSubmit);
            $self->addMessageXML( type => "error", code => RPS::XMLObject::kErrFormSubmit );
        }
    }

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

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

    return $response;
}

1;
