package Distribution::Packager::ShockHound;

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

use Common::Assert;

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

sub _requireAllowed { 1 }

sub _templateFile { 'shockhound.tt' }

sub _albumMetadataName {
    my $self  = shift;
    my $album = shift;
    return $album->{upc} . ".txt";
}

sub _manifestFile { 'manifest.txt' }

sub _serviceCountries { qw( US ) }

sub _prettyPrintXML { }

# No Validation, this is a TSV file
sub _validateWithoutXSD { 1 }

###
#   Album Art
###
sub _imageFormat {
    {
        geometry => '1400x1400',
        density  => 72,
    };
}

###
#   Album Audio
###
sub _audioConverter { 'MediaServe::Audio::Converter::MP3' }
sub _audioConverterOptions { { variable => 2 } }

###
#   Manifest
###

sub _albumManifest {
    my $self  = shift;
    my $album = shift;
    my $count = 0;

    foreach my $volume ( @{ $album->{'volume'} } ) {
        foreach my $track ( @{ $volume->{'track'} } ) {
            $count++;
        }
    }

    my ($genDate) = split( / /, $album->{'generation-date'} );
    return {
        Code       => $album->{'vendor-id'},
        Date       => $genDate,
        Dir        => $self->_distributionPackageName(),
        UPC        => $album->{upc},
        TrackCount => $count
    };

}

sub _manifest {
    my $self = shift;

    my $destFile = $self->_localManifestPath();
    my $output;

    assert($destFile);

    Common::Log::Debug("*** Processing manifest ***");
    Common::Log::Debug(" - Manifest file: $destFile");

    unless ( $self->_processedAlbumsCount() ) {
        Common::Log::Debug(" - No albums processed, not creating manifest");
        return 1;
    }

    if ( $self->{_manifest} ) {
        $output .= sprintf(
            "%s\t%s\t%s\t%s\t%s\n",
            qw(Content_Provider_Name
              Manifest_Creation_Date
              Content_Delivery_ID
              Album_UPC
              Album_Track_Count)
        );

        foreach my $record ( @{ $self->{_manifest}->{Album} } ) {
            $output .=
              sprintf( "%s\t%s\t%s\t%s\t%s\n", $record->{Code}, $record->{Date}, $record->{Dir}, $record->{UPC}, $record->{TrackCount} );
        }
        $self->_writeFile( $self->_localManifestPath(), $output );
    } else {
        Common::Log::Print("WARNING: No manifest data found");
    }

    return 1;
}

1;
