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

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

use lib '/app/tools/rps/lib';
use lib '/app/tools/raptor/lib';
use lib '/app/tools/appuser/lib';
use Raptor::Tracker::Command::Main;
use RPS::Sale::Report;
use AppUser::DB::Item::AccessLevel;

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

sub cmd  { return "trackerdl"; }
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 $clientID = Common::RSApp::GetClientID();

    # We want to supress the 'thousands' separator in this report.
    # So we'll temporarily override the local's numeric formatting flags.
    #
    my $tempSettings = Common::NumericFormat::TemporarySettings( showThousandsFlag => 0 );

    my ( $file, $clientNameClean ) = RPS::Sale::Report->GetTrackerExcelFile($clientID);

    ## delete if exists
    unlink $file if ( -e $file );

    if (   $self->_getUser()->AccessLevel == AppUser::DB::Item::AccessLevel::kRSAccountRep
        || $self->_getUser()->AccessLevel == AppUser::DB::Item::AccessLevel::kRSAdmin ) {

        ## add flag to include notes field
        RPS::Sale::Report->CreateTrackerExcelFile( $clientID, 1 );
    } else {
        RPS::Sale::Report->CreateTrackerExcelFile($clientID);
    }

    if ( -f $file ) {
        my $fh = new IO::File;
        open( $fh, $file );
        my @stat     = $fh->stat;
        my $fileSize = $stat[7];
        return RSApache::Response::Download->new( $fh, 'application/octet-stream', $clientNameClean . "_Summary.xls", $fileSize );
    } else {
        $self->addMessageXML( type => "error", code => "download_unavailable" );
    }

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

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

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

    return $response;
}

1;
