package RPS::Import::EMIUK::Digital;

use strict;

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

use lib '/app/tools/rps/lib';
use base 'RPS::Import::Importer';

use Data::Dumper;

sub _headerIdentifier { ( price => 'NDS Value' ) }

sub currencyCode { 'GBP' }

sub _productTypes {
    {
        'album download' => {
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'bundle download' => {
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'longform download' => {
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'video download' => {
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeVideo,
        },
        'track ringtune' => {
            formatType => RPS::File::Sale::FORMAT_RINGTONE,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'track ringback' => {
            formatType => RPS::File::Sale::FORMAT_RINGTONE,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'track download' => {
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'single download' => {
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'subscr download' => {
            formatType => RPS::File::Sale::FORMAT_TETHERED,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'track stream' => {
            formatType => RPS::File::Sale::FORMAT_STREAM,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'single stream' => {
            formatType => RPS::File::Sale::FORMAT_STREAM,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'album stream' => {
            formatType => RPS::File::Sale::FORMAT_STREAM,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'bundle stream' => {
            formatType => RPS::File::Sale::FORMAT_STREAM,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'clip download' => {
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'clip stream' => {
            formatType => RPS::File::Sale::FORMAT_STREAM,
            mediaType  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
    };
}

# both of the following functions are super awesome because
# they rely on private member functions of the base class.
# we'll just call them "protected"...

sub _overloadedIdentifier {
    my $self = shift;

    my $map = $self->_fieldMap();

    return ( $map->{upc} eq $map->{isrc} );
}

sub _overloadedTitle {
    my $self = shift;

    my $map = $self->_fieldMap();

    return ( $map->{albumName} eq $map->{trackName} );
}

# by default, productType is ambiguous and can't siply be determined by
# grokking EMI's format. rather, we must look at the single identifier
# provided. if it looks like a UPC, it's an album, otherwise a track

sub productType {
    my $self = shift;

    my $productType;

    if ( $self->_overloadedIdentifier() ) {
        my $identifier = $self->SUPER::upc();
        if ( length($identifier) >= 12 && $identifier =~ m/^\d+$/ ) {
            $productType = RPS::File::Sale::TYPE_ALBUM;
        } else {
            $productType = RPS::File::Sale::TYPE_TRACK;
        }
    } else {
        die "Must be overloaded";
    }

    return $productType;
}

sub upc {
    my $self = shift;

    my $upc;
    if ( $self->productType() eq RPS::File::Sale::TYPE_ALBUM
        || !$self->_overloadedIdentifier() ) {
        $upc = $self->SUPER::upc();
    }

    return $upc;
}

sub isrc {
    my $self = shift;

    my $isrc;

    if ( $self->productType() eq RPS::File::Sale::TYPE_TRACK ) {
        $isrc = $self->SUPER::isrc();
    }

    return $isrc;
}

sub albumName {
    my $self = shift;

    my $albumName;

    if ( $self->productType() eq RPS::File::Sale::TYPE_ALBUM
        || !$self->_overloadedTitle() ) {
        $albumName = $self->SUPER::albumName();
    }

    return $albumName;
}

sub trackName {
    my $self = shift;

    my $trackName;

    if ( $self->productType() eq RPS::File::Sale::TYPE_TRACK ) {
        $trackName = $self->SUPER::trackName();
    }

    return $trackName;
}

sub countryCode {
    my $self        = shift;
    my $country     = $self->SUPER::countryCode() || return;
    my $origCountry = $country;

    $country =~ s/EMI //i;
    $country =~ s/Virgin India/India/i;
    $country =~ s/^Arabia$/Saudi Arabia/i;
    $country =~ s/Taiwan \(Gold Typhoon\)/Taiwan/i;

    my $c = new Common::Country( search => $country =~ /Records UK/ ? 'GB' : $country );

    $self->fail("Unable to determine country code from '$origCountry'") unless ($c);

    return $c->alpha2;
}

sub _processHeader {
    my $self = shift;

    return if ( $self->{_dateBegin} );

    my $date = $self->SUPER::_getDateBegin() || return;

    if ( $date =~ /(\w{3} \d{4}$)/ ) {
        my $d = new Common::Date($1);
        $self->{_dateBegin} = $d->monthBegin();
        $self->{_dateEnd}   = $d->monthEnd();
    } elsif ( $date =~ /(\d{4}-\d{2}-\d{2}$)/ ) {
        my $d = new Common::Date($1);
        $self->{_dateBegin} = $d->monthBegin();
        $self->{_dateEnd}   = $d->monthEnd();
    } else {
        print STDERR "DEBUG: _processHeader: Unable to decode date '$date'\n";
    }
}

sub _getDateBegin { shift->{_dateBegin} }
sub _getDateEnd   { shift->{_dateEnd} }

sub _isValidSaleRecord {
    my $self = shift;

    return unless ( $self->SUPER::_isValidSaleRecord );

    # There are summary lines in this file that do not have a format set.
    # These need to be ignored.
    return unless ( $self->_getByFieldName('type') );

    # We want to throw an error if we have zero units and non-zero revenue.
    # case 15801
    if ( $self->price && !$self->units ) {
        $self->fail( "Price " . $self->price . " found with zero units" );
    }

    # sales file includes lines with 0 units or 0 price.  We need to ignore these
    return $self->units || $self->price ? 1 : undef;
}

# For some reason we have negative units and a positive price.  We need to accept
# this value, so we disable the validation.  case 13867
sub _validatePrice {
    my ( $self, $saleRec ) = @_;
    my $price = $saleRec->price || return;

    # 0 | 0.0 | .00 |0.
    if ( $price !~ /^-?(?:(?:\d+)?\.\d+|\d+(?:\.)?(?:\d+)?)$/ ) {
        die Import::ValidationError->new( $saleRec, "Price $price is in an incorrect format" );
    }

}

###
1;    # Play nicely.
###
