#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Raptor::Tracker::Command::Download;
use strict;
use warnings;
use IO::File;

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

use lib '/app/tools/rps/lib';
use lib '/app/tools/raptor/lib';
use Raptor::Tracker::Command::Main;
use RPS::Sale::Report;

use Raptor::Command;
use base 'Raptor::Tracker::Command::Base';

sub cmd  { return "download"; }
sub area { return "tracker"; }

use constant kTemplate => '/app/tools/raptor/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 $period      = new Period::RoyaltyPeriod();
    my $periodParam = $self->getParam('period');
    if ( !$periodParam ) {
        $period->LoadCurrent();
    } else {
        $period->Load( period_id => $periodParam );
    }

    my $fileType = $self->getParam('file_type');

    my $clientID = Common::RSApp::GetClientID();
    my ( $file, $clientNameClean ) = RPS::Sale::Report->GetRoyaltyReportFile(
        period_id => $period->PeriodID,
        client_id => $clientID,
        file_type => $fileType,
    );

    if ( -f $file ) {
        my $periodName = $period->Name;
        $periodName =~ s/\s+/_/g;
        $periodName =~ s/\W//g;

        my $fileName = uc($clientNameClean);
        $fileName .=
            $fileType =~ m/account/i ? '_DGRoy_'
          : $fileType =~ m/recon/i   ? '_AcctRec_'
          : $fileType =~ m/billing/i   ? '_RS_Billing_Report_'
          :                            '_RoyaltyReport_';

        $fileName .= $periodName || sprintf( "%s_to_%s", $period->StartDate, $period->EndDate );

        if ( $file =~ /(\.\w+)$/ ) {
            $fileName .= $1;
        }

        my $fh = new IO::File;
        open( $fh, $file );
        my @stat     = $fh->stat;
        my $fileSize = $stat[7];

        if ( $fileType eq 'royalty' || $fileType eq 'billing' ) {
            return RSApache::Response::DownloadText->new( $fh, 'application/octet-stream', $fileName, $fileSize );
        } else {
            return RSApache::Response::Download->new( $fh, 'application/octet-stream', $fileName, $fileSize );
        }
    } else {

        # do we want to respawn this process? It's possible the
        # original dump_royalty_report.pl is still running, right?

        # dump_royalty_report takes two args: client_id and period_id
        # my $run_report_script = "/app/tools/sale_import/bin/dump_royalty_report.pl -c ".$self->ClientID ." -p".$new_period_id;
        # system("$run_report_script &");
        Common::Log::Print("Unable to file report file $file for download, returning download_unavailable");

        $self->addMessageXML( type => "error", code => "download_unavailable" );

        $self->doFileListing($period);
        $self->{xml}{Report}{Period} = $period->GetObjectXML();
        $self->setExceptionsFileStatus();

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

1;
