#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package BookPub::RDAS::Process::ImportSalesFile;

use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::Assert;

use lib '/app/tools/bookpub/lib';
use BookPub::POS::Tracker::File;
use BookPub::POS::Sale::File;

use base 'BookPub::RDAS::Process';

sub _options {
    {
        client_id => {
            short       => 'c',
            required    => 1,
            description => 'Limit to this client id',
            parameter   => 'i'
        },
        pos_file_id => {
            short       => 'f',
            description => 'File ID to import',
            required    => 1,
            parameter   => 'i'
        },
        service_list => {
            short       => 'y',
            description => 'List all monitored services',
        }
    };
}

sub _process {
    my $self   = shift;
    my $fileID = $self->param('pos_file_id');

    my $file = BookPub::POS::Tracker::File->new( posFileID => $fileID );

    if ( !$file || $file->POSFileID != $fileID ) {
        return $self->error("File ID $fileID was not found.");
    }

    if ( $self->_canImport($file) ) {
        $self->_importFile($file);
    } else {
        Log->notice("File already imported.  Ignoring");
    }

}

sub _canImport {
    my $self = shift;
    my $file = shift;

    assert($file);

    return BookPub::DB::Item::POSFile::STATUS_NEW() == $file->FileStatus
      || BookPub::DB::Item::POSFile::STATUS_IN_QUEUE() == $file->FileStatus;

}

sub _importFile {
    my $self = shift;
    my $file = shift;

    Log->notice("Begin import process");

    Log->info(" Set file status to processing");
    $file->setStatusProcessing();

    # - parse sales file
    my $sf = BookPub::POS::Sale::File->new( client_id => Common::RSApp::GetClientID );
    my $success = $sf->ParseFull( file => $file );

    $file->setStatusOpen() if ($success);
    if ($success) {
        $file->updateSummary();
        $file->save();
    }

    my $error = $sf->errstr;
    Log->info( sprintf( "ParseFull returned '%s', error = '%s'", $success ? $success : '<undef>', $error ? $error : '<undef>' ) );
}

1;
