#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package BookPub::Tracker::Command::RedeliverRoyaltyReport;
use strict;
use warnings;
use Data::Dumper;

use lib '/app/tools/common/lib';
use RSApache::Message;
use RSApache::Response::XSLT;
use Common::DB::Item::ClientFTP;
use Common::RSApp;
use Common::Assert;
use Common::Log;

use lib '/app/tools/bookpub/lib';
use BookPub::Tracker::Job::FTPRoyaltyReport;
use BookPub::Tracker::Command::Main;

use base 'BookPub::Command';

sub cmd      { return "redeliver_royalty_report"; }
sub area     { return "tracker"; }
sub pageName { return "Redeliver Royalty Report"; }

use constant kTemplate => '/app/tools/bookpub/templates/tracker.xsl';

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

    # Give any inherited methods the first crack at this.
    # (This checks for login and basic access permissions).
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $periodID = $self->getParam('period');
    die "ERROR - no period id" unless $periodID;

    my $clientID = Common::RSApp::GetClientID();

    my $clientFTP = Common::DB::Item::ClientFTP->Lookup( client_id => $clientID );

    my $message;

    # We don't want test servers to FTP files unless we're using a test client.
    if ($clientFTP) {
        if ( Common::RSApp::IsProductionServer || $clientID == 310 ) {    # DTMV Test
            my $jobArgs = BookPub::Tracker::Job::FTPRoyaltyReport->new(
                clientID     => $clientID,
                periodID     => $periodID,
                report_email => $clientFTP->email,
                error_email  => $clientFTP->email,
            );
            $jobArgs->enqueue();
            $message = RSApache::Message->new( type => "success", code => "ftp_job_queued" );
        } else {
            $message = RSApache::Message->new( type => "error", code => "disabled_in_dev" );
        }
    } else {
        $message = RSApache::Message->new( type => "error", code => "no_client_ftp" );
    }

    my %showParams = (
        period => $periodID,
        msg    => $message->toString(),
    );

    my $command = BookPub::Tracker::Command::Main->new(%showParams);
    my $url     = $command->getRedirect();

    return RSApache::Response::Redirect->new($url);
}

1;
