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

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

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

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

sub cmd  { return "upload"; }
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 @lightweight_fh = $self->getCGI()->upload('fileUpload');

    my %newParams;
    my $messages;

    foreach my $fh (@lightweight_fh) {
        if ( defined $fh ) {
            my $newFileID;

            eval { $newFileID = $self->uploadFile($fh); };

            if ($@) {

                # If this was an ErrorMessage exception, add the message to the redirect.
                # Otherwise, re-throw it.
                #
                if ( ref $@ && $@->isa('RSApache::Message') ) {
                    my $message = $@;
                    $messages .= $message->toString() . "||";
                } else {
                    die $@;
                }
            }

            if ($newFileID) {

                # Queue up the import job
                #
                my $jobArgs = Raptor::Tracker::Job::ImportSalesFile->new( fileID => $newFileID );
                my $job = $jobArgs->enqueue();
            }
        }
    }

    if ($messages) {
        $newParams{rejected} = $messages;
    }

    # to avoid duplicate file uploads when someone refreshes the page
    # we are going to just redirect instead of posting success xml back.
    #
    my $command = Raptor::Tracker::Command::Main->new(%newParams);
    return RSApache::Response::Redirect->new( $command->getRedirect() );
}

1;
