#------------------------------------------------------------
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::Tracker::Command::Import;
use strict;
use warnings;

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

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::File;
use BookPub::DB::Item::Sale;
use BookPub::Sale::File;
use BookPub::Tracker::Job::ImportSalesFile;

use BookPub::Tracker::Command::Main;

use base 'BookPub::Command';

sub cmd      { return "import"; }
sub area     { return "tracker"; }
sub pageName { return 'Revenue File Upload'; }

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 $fileID = $self->getParam('file');
    assert($fileID);

    # Sanity-check a few things - We want to make sure we're prepared to import this file.
    #
    my $file = BookPub::DB::Item::File->Lookup( file_id => $fileID );
    die "ERROR - invalid file id $fileID" unless $file;
    die "ERROR - file $fileID is not in the correct state" unless BookPub::DB::Item::File::STATUS_NEW = $file->file_status();

    my $sales = BookPub::DB::Item::Sale->GetAllByFileID($fileID);
    die "ERROR - file $fileID still has sales associated with it, we cannot re-import" unless 0 == $sales->size();

    my $jobArgs = BookPub::Tracker::Job::ImportSalesFile->new( fileID => $fileID );
    my $job = $jobArgs->enqueue();

    my $command = BookPub::Tracker::Command::Main->new();
    return RSApache::Response::Redirect->new( $command->getRedirect() );
}

1;
