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

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

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 "error_log"; }
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();
    $period->LoadCurrent();

    my $fileID = $self->getParam('file');
    my $file = RPS::File::File->new( file_id => $fileID );

    if ( $file && $file->FileID == $fileID ) {
        my $filePath = $file->GetErrorLog();
        if ( -e $filePath ) {
            open my $fh, "< $filePath";
            my $tmp_name;
            ( $tmp_name = $filePath ) =~ s/.*\/(.*)$/$1/;
            $response = RSApache::Response::DownloadText->new( $fh, 'application/octet-stream', $tmp_name );
            return $response;
        } else {
            $self->addMessageXML( type => 'error', code => 'download_unavailable' );
        }
    }

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

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

    return $response;
}

1;
