package BookPub::RDAS::Response::POSData::Amazon;

use IO::Uncompress::Gunzip;
use File::Temp;

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

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

use base 'BookPub::RDAS::Response::POSData';

sub serviceID { return BookPub::Tracker::Service::AMAZON() }

sub _validOptions {
    return ( shift->SUPER::_validOptions, 'reports', 'reportDate' );
}

sub _saveReport {
    my $self = shift;
    my %args = @_;
    my $file = $args{file};

    my $content;

    assert($file);

    my $outputFilename = $file->Filename;
    $outputFilename =~ s/\.gz$//;

    my ( $year, $month, $day ) = $outputFilename =~ /seller_of_record_(\d{4})(\d{2})(\d{2})/;

    my $length = length( $file->Content );

    Log->info( "Storing report " . $file->Filename . ", length: $length" );

    my $tmpfile = new File::Temp( UNLINK => 1 );
    open( OUT, "> $tmpfile" );

    print OUT $file->Content;
    close OUT;

    open( INFILE, "$tmpfile" );
    while (<INFILE>) {
        $content .= $_;
    }

    my $md5 = Common::Util::md5sum($tmpfile);
    die "MD5 calculation failed" unless ($md5);

    my $fileID = BookPub::POS::Sale::File::SimpleUploadFromMemory(
        client_id   => Common::RSApp::GetClientID(),
        content     => $content,
        filename    => $file->Filename,
        pos_feed_id => $self->feed->POSFeedID,
        md5         => $md5,
        date_start  => $file->StartDate,
        date_end    => $file->EndDate
    );

    $self->_enqueueImportJob($fileID) if ($fileID);

    if ( $year && $month && $day ) {

        # Save the last download date unless we are running for a user specified date
        $self->feed->setLastDownload("$year-$month-$day") unless ( $self->reportDate );
    }

}

1;
