#!/usr/bin/perl
#

use strict;

FtpReport->start();

package FtpReport;

use lib '/app/tools/bookpub/lib';
use BookPub::Tracker::Command::RSFTP;
use BookPub::Sale::Report::Royalty::Factory;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::RSApp;
use Common::Email;
use Common::DB::Item::Client;
use Common::DB::Item::ClientFTP;

use base 'Common::CronScript';

sub _options {
    {
        client_id => {
            short       => 'c',
            required    => 1,
            description => 'RoyaltyShare client id',
            parameter   => 'i'
        },
        period_id => {
            short       => 'p',
            required    => 1,
            description => 'Period id',
            parameter   => 'i'
        }
    };
}

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

    my $clientID = $self->param('client_id');
    my $periodID = $self->param('period_id');

    my $royaltyReport = BookPub::Sale::Report::Royalty::Factory::GetRoyaltyReport($periodID);

    my $fileName;
    my $transferType;

    # Let's see if we need to send a zip file for this client.
    if ( sendZip($clientID) ) {
        $fileName     = $royaltyReport->zipFilePath();
        $transferType = 'binary';
    } else {
        $fileName     = $royaltyReport->filePath();
        $transferType = 'ascii';
    }

    my $client = Common::DB::Item::Client->Lookup( client_id => $clientID );
    my $clientName = $client->client_name;

    print "Client: $clientName\n";
    print "Period ID: $periodID\n";
    print "File: $fileName\n";
    print "Time: " . localtime() . "\n\n";

    # check that file exists
    unless ( -e $fileName ) {
        print "Error: $fileName does not exist\n";
        return 0;
    }

    my $coll = Common::DB::Item::ClientFTP->GetFtpData($clientID);

    while ( $coll->hasNext() ) {

        my $dbItem = $coll->next();

        # if this clientID has an entry in the database and its status is active,
        # then do the transfer
        if ( $dbItem && $dbItem->status eq 'active' ) {

            my $transfer = BookPub::Tracker::Command::RSFTP->execute(
                FtpSite    => $dbItem->ftp_site,
                Username   => $dbItem->username,
                Password   => $dbItem->password,
                TargetDir  => $dbItem->target_dir,
                Protocol   => $dbItem->protocol,
                PrivateKey => $dbItem->private_key,
                FilePath   => $fileName,
                Type       => $transferType
            );
            print "$transfer\n\n";
        } else {
            print "File not transferred, client has not requested file transfer\n\n";
        }
    }
}

sub sendZip {
    my $clientID = shift;

    # Currently only three clients receives a zip file through FTP.
    return 1
        if $clientID == 365    # SAGE
        || $clientID == 348    # MMAU
        || $clientID == 617    # MMAU Print
    ;

    return 0;
}
