package Distribution::Packager::iTunes;

use strict;
use Data::Dumper;
use File::Basename;

use Common::Assert;

use lib '/app/tools/distribution/lib';
use Distribution::TransportAgent::ITMS;

use base 'Distribution::PackagerNew';

sub _templateFile { 'itunes.tt' }

sub _requireAllowed { 1 }

sub _albumMetadataName { 'metadata.xml' }

sub _serviceCountries {
    my @countries;

    push(
        @countries,

        # US / Canada
        qw( US CA ),

        # Japan
        qw( JP ),

        # Australia / New Zeland
        qw( AU NZ ),

        # Europe
        qw( AT BE CH CY CZ DE DK EE ES FI FR GR GB HU IE IS IT LI LT LU LV MT NL NO PL PT SE SI SK )
    );

    return @countries;
}

sub _worldWideTerritory { 'WW' }

sub _albumPackageName { shift->SUPER::_albumPackageName(@_) . ".itmsp"; }

###
#   Album Art
###
sub _imageFormat {
    {
        geometry => '600x600',
        density  => 200,
    };
}

sub _albumImageName {
    my $self = shift;
    my $album = shift || die "album required";

    assert( $album->{upc} );

    return $album->{upc} . "_cover.jpg";
}

###
#   Album Audio
###
sub _audioConverter { 'MediaServe::Audio::Converter::FLAC' }

sub _albumAudioFileExtension { 'flac' }

sub _albumAudioFileName {
    my $self   = shift;
    my $album  = shift || die "album required";
    my $volume = shift || die "track required";
    my $track  = shift || die "track required";

    assert( $album->{upc} );

    return sprintf( "%s_%02d_%03d.%s",
        $album->{upc}, $volume->{sequence}, $track->{sequence}, $self->_albumAudioFileExtension( $album, $volume, $track ) );
}

# Use ITMS to validate the metadata.
sub _postPackage {
    my $self = shift;
    my $base = $self->_localDistributionPath();

    $self->SUPER::_postPackage();

    my @albums_processed = @{ $self->{_albumsProcessed} };

    return 1 unless (@albums_processed);

    # We want to validate that albums will be delivered
    my $agentObj = Distribution::TransportAgent::ITMS->new(
        account_name => $self->{_acctInfo}->Code(),
        port         => $self->{_acctInfo}->Port(),
        protocol     => $self->{_acctInfo}->Protocol(),
        user         => $self->{_acctInfo}->Username(),
        passwd       => $self->{_acctInfo}->Password(),
        host         => $self->{_acctInfo}->Hostname(),
        dont_retry   => 1,
        testing      => 1
    );

    my ($ok) = $agentObj->deliver("$base");
    unless ($ok) {
        print STDERR "- Failed validation\n\n";
        return;
    }

    return 1;
}

1;
