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

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

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

use lib '/app/tools/rps/lib';
use RPS::RoyaltyRun::RoyaltyRunStatusList;
use RPS::Sale::Report;
use RPS::DB::Item::ClientOptions;

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

sub cmd  { return "main"; }
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;

    $self->{xml}{GrossRevenueEnabled} = RPS::DB::Item::ClientOptions->Get( 'gross_revenue' );

    my @rejectedFiles;
    my $rejectedFiles = $self->getParam('rejected');
    if ($rejectedFiles) {
        my @rejectedArray = split( /\|\|/, $rejectedFiles );
        foreach my $rejectedFile (@rejectedArray) {
            my %rejectedHash;
            my @rejectedSplit = split( /\|/, $rejectedFile );
            $rejectedHash{FileName} = $rejectedSplit[1];
            $rejectedHash{Code}     = $rejectedSplit[2];
            push @rejectedFiles, \%rejectedHash;
        }
        $self->{xml}{RejectedFiles}{RejectedFile} = \@rejectedFiles;
    }

    my $period      = new Period::RoyaltyPeriod();
    my $periodParam = $self->getParam('period');
    if ( !$periodParam ) {
        $period->LoadCurrent();
    } else {
        $period->Load( period_id => $periodParam );
    }

    # Only do run control for the current period (0)
    unless ($periodParam) {
        my $form = { RoyaltyRunStatus => new RPS::RoyaltyRun::RoyaltyRunStatusList() };
        $self->{xml}{Form} = $form;
    }

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

    # I also want to indicate which (if any) of the reports are available for download.
    #
    my %reportStatus;
    foreach my $fileType ( 'royalty', 'royalty_excel', 'royalty_consolidation', 'reconciliation', 'royalty_xml', 'accounting', 'billing' ) {
        my $srcFile = RPS::Sale::Report->GetRoyaltyReportFile(
            client_id => Common::RSApp::GetClientID(),
            period_id => $periodParam,
            file_type => $fileType
        );
        if ( $srcFile && -f $srcFile ) {
            $reportStatus{$fileType} = 1;
        }
    }
    $self->{xml}{Report}{FileStatus} = \%reportStatus;

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

    return $response;
}

1;
