package BookPub::RDAS::Response::POSData::Apple;

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::APPLE() }

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 =~ /(\d{4})(\d{2})(\d{2})\./;

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

    Log->info("Storing report $filename, length: $length");

    # This fails based on content encoding:
    #
    # Don't know how to decode Content-Encoding 'agzip' at /usr/local/share/perl/5.10.0/HTTP/Message.pm line 354.
    #    ...propagated at /app/tools/bookpub/lib/BookPub/RDAS/Response/POSData/Apple.pm line 48.
    # my $output;
    # my $success = IO::Uncompress::Gunzip::gunzip( $report, \$output );

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

    print ZCAT $file->Content;
    close ZCAT;

    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    => $outputFilename,
        pos_feed_id => $self->feed->POSFeedID,
        md5         => $md5,
        date_start  => $file->StartDate,
        pos_file_id => $file->POSFileID,
        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;
