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

use lib '/app/tools/bookpub/lib';
use BookPub::Market::WatchListForm;
use BookPub::Market::Command::Main;
use BookPub::Catalog::ImprintList;
use BookPub::Catalog::PublisherList;
use BookPub::Catalog::ServiceList::WatchList;

use base 'BookPub::Command';

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

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

sub pageName {
    my ($self) = @_;
    my $watchListID = $self->getParam('WatchListID');
    if ($watchListID) {
        return 'Edit Watch List';
    } else {
        return 'Create Watch List';
    }
}

use constant kTemplate => "/app/tools/bookpub/templates/market/edit.xsl";

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

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

    my $params = $self->getParams();

    my $form;
    my $watchListID = $self->getParam('WatchListID');
    if ($watchListID) {
        $form = BookPub::Market::WatchListForm->new( watchListID => $watchListID );
    } else {
        $form = BookPub::Market::WatchListForm->new();
    }

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

            if ( !$watchListID ) {
                $watchListID = $form->{WatchList}->WatchListID();
                assert( $watchListID, "Hmm - no watch list id" );
            }

            # We want to change views, so we want to redirect to the main command now.
            my %mainParams = ( WatchListID => $watchListID, );

            my $command = BookPub::Market::Command::Main->new(%mainParams);
            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;

    $self->{xml}{PublisherList} = BookPub::Catalog::PublisherList->new();
    $self->{xml}{ImprintList}   = BookPub::Catalog::ImprintList->new();
    $self->{xml}{ServiceList}   = BookPub::Catalog::ServiceList::WatchList->new();

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

1;
