package RPS::Import::UniversalUKDigital;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_Month);

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

use lib '/app/tools/rps/lib';
use RPS::File::Sale;
use RPS::Import::Importer;
use RPS::Import::ServiceMap;

use base 'RPS::Import::MapFaceBase';
use base 'RPS::Import::Importer';

my %product_format_map = (
    'FULL TRACK DOWNLOAD MOBILE'       => RPS::File::Sale::FORMAT_DOWNLOAD,
    'PERMANENT DOWNLOAD'               => RPS::File::Sale::FORMAT_DOWNLOAD,
    'PERMANENT DOWNLOAD MOBILE'        => RPS::File::Sale::FORMAT_DOWNLOAD,
    'SUBSCRIPTION DOWNLOAD'            => RPS::File::Sale::FORMAT_VPD,
    'MOBILE STREAMING (AUDIO & VIDEO)' => RPS::File::Sale::FORMAT_STREAM,
    'STREAMING'                        => RPS::File::Sale::FORMAT_STREAM,
    'SUBSCRIPTION STREAMING'           => RPS::File::Sale::FORMAT_STREAM,
    'AD-FUNDED STREAMING'              => RPS::File::Sale::FORMAT_STREAM,
    'WEBCASTING/SIMULCASTING'          => RPS::File::Sale::FORMAT_STREAM,
    'WEBCASTING / SIMULCASTING'        => RPS::File::Sale::FORMAT_STREAM,
    'CLOUD SERVICE'                    => RPS::File::Sale::FORMAT_STREAM,
    'COMES WITH MUSIC DOWNLOAD'        => RPS::File::Sale::FORMAT_TETHERED,
    'COMES WITH MUSIC DOWNLOADS'       => RPS::File::Sale::FORMAT_TETHERED,
    'DOWNLOAD PORTABLE DEVICE'         => RPS::File::Sale::FORMAT_TETHERED,
    'PORTABLE SUBSCRIPTION'            => RPS::File::Sale::FORMAT_TETHERED,
    'PREMIUMS (DIGITAL)'               => RPS::File::Sale::FORMAT_DOWNLOADPREMIUM,
);

sub _fieldMap {
    {
        dateBegin   => 'A',
        countryCode => 'B',
        serviceID   => 'E',
        labelName   => 'F',
        productType => 'G',
        isrc        => 'H',
        trackName   => 'K',
        formatType  => 'M',
        upc         => 'N',
        albumName   => 'P',
        units       => 'Q',
        price       => 'U',
    };
}

sub _unverifiedFieldMap {
    {
        trackArtist => 'I',
        albumArtist => 'O',
    };
}

sub _headerIdentifier { ( upc => 'UPC (Reported)' ) }

sub currencyCode { 'GBP' }

sub saleDates {
    my $self = shift;
    my $dt   = $self->_getByFieldName('dateBegin');

    my $dateBegin;
    my $dateEnd;

    if ( $dt =~ /^(\d{4})(\d{2})$/ )    # YYYYMM
    {
        my $year  = $1;
        my $month = $2;
        $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
        $dateEnd = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
    } else {
        ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $dt );
    }
    return ( $dateBegin, $dateEnd );
}

sub countryCode {
    my $self  = shift;
    my $cname = $self->_getByFieldName('countryCode');
    my $o     = Common::Country->Get($cname);
    if ( !$o ) {
        return $cname;    # Must original name and let MapFace deal with it
    }
    return $o->alpha2;
}

sub serviceID {
    my $self        = shift;
    my $serviceName = $self->_getByFieldName('serviceID');
    my $serviceID   = $self->getServiceID( lc($serviceName) ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $serviceName };

    if ( !$serviceID ) {
        return $self->handleError( "Unknown service: $serviceName", RPS::DB::Item::SaleImportError::kErrorService );
    }

    return $serviceID;
}

sub productType {
    my $self = shift;
    my $type = $self->_getByFieldName('productType');

    if ( $type =~ /^album\/multi track single$/i ) {
        return RPS::File::Sale::TYPE_ALBUM;
    } elsif ( $type =~ /^(video|track)$/i ) {
        return RPS::File::Sale::TYPE_TRACK;
    }
    return $self->handleError( "Unknown product: $type", RPS::DB::Item::SaleImportError::kErrorProductType );
}

sub formatType {
    my $self   = shift;
    my $type   = $self->_getByFieldName('formatType');
    my $format = $product_format_map{ uc $type };

    if ( !$format ) {
        return $self->handleError( "Unknown format: $type", RPS::DB::Item::SaleImportError::kErrorFormatType );
    }
    return $format;
}

sub mediaType {
    my $self = shift;
    my $type = $self->_getByFieldName('productType');

    if ( $type =~ /video/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    } else {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    }
}

sub artistName {
    my $self        = shift;
    my $trackArtist = $self->_getByFieldName('trackArtist');
    my $albumArtist = $self->_getByFieldName('albumArtist');

    if ( $self->productType eq RPS::File::Sale::TYPE_ALBUM ) {
        return $albumArtist;
    } elsif ( $self->productType eq RPS::File::Sale::TYPE_TRACK ) {
        return $trackArtist;
    }

    if ( !defined $self->productType ) {
        return ( defined $trackArtist && '' ne $trackArtist ) ? $trackArtist : $albumArtist;
    }
}

sub units {
    my $self  = shift;
    my $units = $self->SUPER::units();
    my $price = $self->SUPER::price();

    # The 'sign' of the units is driven by the price.
    # If the price is negative, we'll store negative units,
    # regardless of whether the units were positive or negative
    # in the sale file.  Accordingly, the price is always
    # positive.  This ensures that returns are recorded correctly.
    #
    if ( defined($price) && $price != 0 ) {
        return $price < 0 ? abs($units) * -1 : abs($units);
    } else {
        return $units;
    }
}

sub unitPrice {
    my $self = shift;
    return ( 0 == $self->price ) ? 0 : $self->SUPER::unitPrice();
}

#####    MapFace    #####
#

sub _mapFaceServiceID {
    return ('serviceID');
}

sub _mapFaceCountryCode {
    return ('countryCode');
}

sub _mapFaceProductType {
    return ('productType');
}

sub _mapFaceFormatType {
    return ('formatType');
}

sub _mapFaceMediaType {
    return ('productType');
}

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