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

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

use lib '/app/tools/rps/lib';
use RPS::Sale::Report;

use lib '/app/tools/raptor/lib';
use Raptor::Tracker::Command::Main;
use Raptor::Tracker::Job::DumpRoyaltyReport;

use Raptor::Command;
use base 'Raptor::Command';

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

use lib '/app/tools/job/lib';
use Job::Job;

sub cmd  { return "redo_reports"; }
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 $periodParam = $self->getParam('period');
    die "ERROR - no period specified" unless $periodParam;

    # Let's make sure this is a _valid_ period...
    #
    my $period = new Period::RoyaltyPeriod();
    if ( !$period->Load( period_id => $periodParam ) ) {
        die "ERROR - cannot load period $periodParam";
    }

    # We're going to want to remove the old files.
    # !!! This isn't something we want to do a _lot_...
    # !!! We could rename the files for backup purposes.
    #
    my $backupSuffix = 'backup_' . time();
    foreach my $fileType ( 'royalty', 'royalty_excel', 'royalty_consolidation', 'reconciliation', 'royalty_xml', 'billing' ) {
        my $srcFile = RPS::Sale::Report->GetRoyaltyReportFile(
            client_id => Common::RSApp::GetClientID(),
            period_id => $periodParam,
            file_type => $fileType
        );
        if ( $srcFile && -f $srcFile ) {
            my $newName = $srcFile . '_' . $backupSuffix;
            if ( !rename( $srcFile, $newName ) ) {
                die "Error - Unable to rename $srcFile to $newName: $!";
            }
        }
    }

    # Kick off the job to re-build the reports.
    #
    my $jobArgs = Raptor::Tracker::Job::DumpRoyaltyReport->new( periodID => $periodParam );
    my $job = $jobArgs->enqueue();

    return RSApache::Response::Redirect->new("/app/tracker?period=$periodParam");
}

1;
