#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#---------------------------------------------------------------
package BookPub::Catalog::Command::EditChapter;
use strict;
use warnings;

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

use BookPub::Catalog::EditChapterForm;
use BookPub::Catalog::Command::ShowBook;

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'; }
sub area     { return 'catalog'; }
sub pageName { return 'Edit Chapter'; }

use constant kTemplate => "/app/tools/bookpub/templates/catalog/edit_chapter.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 $bookID    = $self->getParam('BookID');
    assert( $bookID || $chapterID );

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

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

            if ( !$bookID ) {
                $bookID = $form->{Chapter}->BookID();
            }

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

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

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

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