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

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

use lib '/app/tools/bookpub/lib';
use BookPub::RDAS::Service;
use BookPub::RDAS::Request::POSData;

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

sub _options {
    my $self    = shift;
    my $options = $self->SUPER::_options(@_);

    $options->{service_id} = {
        short       => 's',
        description => 'Limit to this service id',
        parameter   => 'i'
    };

    $options->{date} = {
        short       => 't',
        description => 'Date of sales to download',
        parameter   => 's'
    };

    $options->{retry} = {
        short       => 'r',
        description => 'Retry a pos file import by pos file id',
        parameter   => 'i'
    };

    return $options;
}

sub _jobClass { 'BookPub::RDAS::Job::FetchPOSFile' }

sub _process {
    my $self = shift;

    my @ids = $self->_getServiceIDs();

    Log->info( "Running URL update for client " . $self->param('client_id') . " on services: @ids" );
    foreach my $id (@ids) {
        $self->_processService($id);
    }
}

sub _processService {
    my $self      = shift;
    my $serviceID = shift;

    Log->debug("** Begin service process, Service ID: $serviceID");

    my %args;

    if ( $self->param('date') ) {
        my $date = new Common::Date( $self->param('date') );
        %args = ( reportDate => $self->param('date') );
    }

    $args{retry} = $self->param('retry');

    my $request = BookPub::RDAS::Request::POSData->GetRequestObject( $serviceID, %args );

    $request->run();
}

sub _getServiceIDs {
    my $self = shift;

    if ( $self->param('retry') ) {
        my $dbItem = BookPub::DB::Item::POSFile->Lookup( pos_file_id => $self->param('retry') );
        die "File not found" unless ($dbItem);

        return ( $dbItem->service_id );
    }

    return $self->SUPER::_getServiceIDs();
}

1;
