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

use Data::Dumper;

use lib '/app/tools/rps/lib';

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

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

sub cmd { return "edit"; }

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

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

    my $trackLicenseID = $self->getParam('TrackLicenseID');
    my $trackID        = $self->getParam('TrackID');
    my $form;
    if ($trackLicenseID) {

        # !!! The 'old way' would dynamically re-cast objects into the right class.
        # !!! Not going to do that anymore.  So we will need to _know_, here, whether we're
        # !!! wanting to edit a track license, or a public domain, or c-comp, or whatever.
        #
        $form = $self->_form()->new( trackLicenseID => $trackLicenseID );
    } elsif ($trackID) {
        $form = $self->_form()->new(
            trackID                 => $trackID,
            licenseType             => $self->getParam("LicenseType"),
            parentTrackLicenseID    => $self->getParam("ParentTrackLicenseID"),
            controlledCompositionID => $self->getParam("ControlledCompositionID")
        );
    }

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

            # Command succeeded, log it.
            RPS::CommandLog::Log( $self, $form->trackLicenseID() );

            # We want to change views, so we want to redirect to the Show command now.
            my $successMessage = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessFormSubmit );
            my $showParams = $self->getPassThroughParams();
            $showParams->{AlbumID} = $form->Track()->AlbumID();
            $showParams->{msg}     = $successMessage->toString();

            # Try to land on the License tab.
            $showParams->{tab} = $self->_tab();

            my $command = RPS::Catalog::Command::Show->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}, $self->_template() );

    return $response;
}

1;
