package Distribution::Delivery::iTunes;

use strict;

use Carp;
use Data::Dumper;
use File::Copy;
use File::Basename;
use List::Compare;

use lib '/app/tools/distribution/lib';
use base 'Distribution::Delivery';

sub _transportAgent { 'Distribution::TransportAgent::ITMS' }

sub _deliver {
    my $self = shift;

    Common::Log::Print("**** Deliver ****");

    my $transportAgent = $self->_getTransportAgent();
    my $sourcePath     = $self->_getLocalPackagePath();

    Common::Log::Debug(" - Source: $sourcePath ");

    $transportAgent->deliver($sourcePath);

    $self->{_successUPCs} = $transportAgent->Successes();
    $self->{_failedUPCs}  = $transportAgent->Failures();

    return 1;
}

sub _finalize {
    my $self    = shift;
    my @success = @{ $self->{_successUPCs} }
      if ( $self->{_successUPCs} );
    my @failed = @{ $self->{_failedUPCs} }
      if ( $self->{_failedUPCs} );

    Common::Log::Print("**** Finalize (custom) ****");

    $self->_processSuccess(@success);
    $self->_processFailed(@failed);

    if (@failed) {
        Common::Log::Print(" - Failure detected!");

        return $self->_retryDelivery();
    }

    return 1;
}

sub _preFinalize {
    my $self    = shift;
    my $srcPath = $self->_getLocalPackagePath();
    my $count   = 0;

    Common::Log::Print("**** Pre Finalize (custom) ****");

    # Count the number of packages we should have transfered
    opendir( SRCDIR, $srcPath );

    foreach my $package ( readdir(SRCDIR) ) {
        next unless ( $package =~ /itmsp$/ );
        $count++;
    }

    $self->{_albumCount} = $count;

    return 1;
}

sub _postFinalize {
    my $self = shift;

    Common::Log::Print("**** Post Finalize (custom) ****");

    # Verify that we have an accurate delivery count.  This test ensures that we
    # Are properly parsing the ITMS output.

    my @success = @{ $self->{_successUPCs} }
      if ( $self->{_successUPCs} );

    my @failed = @{ $self->{_failedUPCs} }
      if ( $self->{_failedUPCs} );

    my $successes = @success;
    my $failures  = @failed;

    Common::Log::Debug(" Successes: $successes, Failures: $failures, Processed: $self->{_albumCount} ");

    if ( $self->{_albumCount} != ( $successes + $failures ) ) {
        Common::Log::Debug(" - Failed to parse Transporter output!");
        return;
    }

    return 1;
}

sub _processSuccess {
    my $self    = shift;
    my $srcPath = $self->_getLocalPackagePath();

    my @success = @{ $self->{_successUPCs} }
      if ( $self->{_successUPCs} );

    Common::Log::Debug(" Processing successes: @success");

    return unless (@success);

    foreach my $upc (@success) {
        Common::Log::Debug(" - Moving $srcPath/$upc.itmsp to $srcPath/$upc.complete");
        File::Copy::move( "$srcPath/$upc.itmsp", "$srcPath/$upc.complete" );

        Distribution::DB::Item::ProductDistribution->SetDeliveryDateByUPC( $upc, 11 );
    }
}

sub _processFailed {
    my $self    = shift;
    my $srcPath = $self->_getLocalPackagePath();

    my @failure = @{ $self->{_failedUPCs} }
      if ( $self->{_failedUPCs} );

    Common::Log::Debug(" Processing failures: @failure");

    return unless (@failure);

    foreach my $upc (@failure) {
        Distribution::DB::Item::ProductDistribution->SetDeniedByUPC( $upc, 11, "Delivery Failure" );
    }
}

sub _parseChecksum {
    my $self = shift;
    my $file = shift;
    my ( $key, $value );
    my %result;

    open( INFILE, $file ) || confess "Can't read $file";

    while (<INFILE>) {
        ( $key, $value ) = split(/\t/);
        $key = basename($key);
        $result{$key} = $value;
    }

    close(INFILE);

    return \%result;
}

sub _parseDeliveryLog {
    my $self = shift;
    my $file = shift;
    my %result;
    my ( $key, $value );

    open( INFILE, $file ) || confess "Can't read $file";

    while (<INFILE>) {
        ( $key, $value ) = split(/\t/);
        $key = basename($key);
        $result{$key} = $value;
    }

    close(INFILE);

    return \%result;
}

1;
