#------------------------------------------------------------
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::Catalog::Command::EditChapterProduct;
use strict;
use warnings;

use lib '/app/tools/bookpub/lib';

use BookPub::Catalog::EditChapterProductForm;
use BookPub::Catalog::Command::ShowChapter;

use base 'BookPub::Command';

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

sub cmd      { return 'edit_chapter_product'; }
sub area     { return 'catalog'; }
sub pageName { return 'Edit Chapter Product'; }

use constant kTemplate => "/app/tools/bookpub/templates/catalog/edit_chapter_product.xsl";

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

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

    Common::Log::Print( "PARAMS: " . $self->getParamsAsString() );

    my $form;
    my $chapterID = $self->getParam('ChapterID');
    my $productID = $self->getParam('ProductID');
    assert( $chapterID || $productID );

    if ($productID) {
        $form = BookPub::Catalog::EditChapterProductForm->new( productID => $productID );
    } else {
        $form = BookPub::Catalog::EditChapterProductForm->new( chapterID => $chapterID );
    }

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

            if ( !$chapterID ) {
                $chapterID = $form->{ChapterProduct}->ChapterID();
            }

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

            # We want to change views, so we want to redirect to the Show command now.
            #
            my %showParams = (
                ChapterID => $chapterID,

                #				msg => 'Book Successfully Created',
            );

            my $command = BookPub::Catalog::Command::ShowChapter->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;
