package RPS::Import::AWAL::v4;

use strict;
use warnings;

use parent ( 'RPS::Import::MapFaceBase', 'RPS::Import::AWAL::v3');

use Date::Calc qw(Decode_Month Days_in_Month);

sub _fieldMapExtended {
    {
        mixed => {
            option1 => {
                labelName    => 'U',
                serviceID    => 'D',
                countryCode  => 'Z',
                dateBegin    => 'AD',
                dateEnd      => 'AE',
                formatType   => 'V',
                upc          => 'L',
                albumName    => 'I',
                isrc         => 'P',
                trackName    => 'Q',
                units        => 'AG',
                currencyCode => 'AJ',
                retailPrice  => 'AK',
                totalRevenue => 'AP',
                price        => 'AP',
                mediaType    => 'T',
                grossRevenue => 'AL',
            },
        },
    };
}

sub _unverifiedFieldMapExtended {
    {
        mixed => {
            option1 => {
                _netUnits        => 'AG',
                _trackArtist     => 'S',
                _bundleArtist    => 'K',
                _productTypePhys => 'M',
                _productTypeDig  => 'F',
            },
        }
    };
}

sub serviceID {
    my $self = shift;

    my $formatType = $self->_getByFieldName('formatType') || '';
    if ( $formatType =~ /^Physical Distribution\s?(?:Via a Distributor|,Kobalt Direct)$/i ) {
        return Client::Service::DSP_ORCHARD;
    }

    my $service   = lc( $self->_getByFieldName('serviceID') || '' );
    my $serviceID = $self->getServiceID($service) || $RPS::Import::ServiceMap::SERVICE_ALIASES{$service};
    return $serviceID if $serviceID;

    return $self->handleError( "Unknown service: '$service'", RPS::DB::Item::SaleImportError::kErrorService );
}

sub productType {
    my $self = shift;

    my $productTypePhys = $self->_getByFieldName('_productTypePhys') || '';
    my $formatType      = $self->_getByFieldName('formatType')       || '';
    if ( $formatType =~ /^Physical Distribution\s?(?:Via a Distributor|,Kobalt Direct)$/i ) {
        return RPS::File::Sale::TYPE_CD if $productTypePhys =~ /.*(?:CD|DS|02)[a-z]*$/i;
        return RPS::File::Sale::TYPE_LP if $productTypePhys =~ /.*(?:LP|01|10)[a-z]*$/i;
        return RPS::File::Sale::TYPE_CASS if $productTypePhys =~ /.*(?:04)[a-z]*$/i;
    }

    my $productTypeDig = $self->_getByFieldName('_productTypeDig') || '';
    if ( $productTypeDig ) {
        return RPS::File::Sale::TYPE_TRACK if $productTypeDig =~ /^Track$/i;
        if ( $productTypeDig =~ /^Bundle$/i ) {
            return $self->isrc ? RPS::File::Sale::TYPE_TRACK : RPS::File::Sale::TYPE_ALBUM;
        }
    } else {
        my $isrc = $self->_getByFieldName('isrc') || '';
        return $isrc ? RPS::File::Sale::TYPE_TRACK : RPS::File::Sale::TYPE_ALBUM;
    }

    $self->fail("Unable to determine product type from '$productTypePhys' or '$productTypeDig'");
}

my %months = (
    jan => 1,
    feb => 2,
    mar => 3,
    apr => 4,
    may => 5,
    jun => 6,
    jul => 7,
    aug => 8,
    sep => 9,
    oct => 10,
    nov => 11,
    dec => 12,
);

sub saleDates {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin');
    my $startDate;
    my $endDate;

    if ( $date =~ /(\d{1,2})-([a-z]{3})-(\d{2})/i ) {
        $startDate = sprintf "%04d-%02d-%02d", "20$3", $months{lc($2)}, $1;
    }
    elsif ( $date =~ /(\d{1,2})[.-](\d{1,2})[.-](\d{4})/ ) { # DD.MM.YYYY
        $startDate = sprintf "%04d-%02d-%02d", "$3", $2, $1;
    }
    elsif ( $date =~ /^\d+$/) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
        ($startDate, $endDate) = $self->SUPER::_getDates( date_begin => $date, type => 'iso' );
    }

    if (!$endDate && $startDate && $startDate =~ /^(\d{4})-(\d\d)-\d\d$/){
        $endDate = sprintf( "%04d-%02d-%02d", $1, $2, Days_in_Month( $1, $2 ) );
    }

    return ( $startDate, $endDate ) if ($startDate && $endDate);

    $self->fail("Unable to determine dates from '$date'");
}

sub formatType {
    my $self = shift;

    my $formatType = $self->_getByFieldName('formatType') || '';
    my $service    = $self->_getByFieldName('serviceID')  || '';

    # RSD-11462
    if ( $self->serviceID == Client::Service::DSP_SOUNDEXCHANGE ) {
        return RPS::File::Sale::FORMAT_NON_EPHEMERAL;
    }

    if ( $formatType =~ /^permanent download$/i ) {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    }
    if ( $formatType =~ /^conditional download$/i ) {
       return RPS::File::Sale::FORMAT_TETHERED;
    }
    if ( $service =~ /pandora/i && $formatType =~ /^(?:non-interactive streaming)$/i) {
        return RPS::File::Sale::FORMAT_PERFORMANCE;
    }
    if ( $formatType =~ /^(?:Cable Radio|Internet Radio and Webcasting|Unidentified Public Performance and Broadcast|Public Performance|Radio Broadcast|TV Broadcast|Exclusive Rights)$/i) {
        return RPS::File::Sale::FORMAT_PERFORMANCE;
    }
    if ( $formatType =~ /^(?:(?:Unidentified )?Private Copying(?: - Audio.*?)?|Music Dubbing)$/i) {
        return RPS::File::Sale::FORMAT_EPHEMERAL;
    }
    if ( $formatType =~ /^(?:non-interactive streaming|on demand streaming|pro rata share of one-off income)$/i ) {
        return RPS::File::Sale::FORMAT_STREAM;
    }

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

sub countryCode {
    my $self = shift;

    my $country = $self->_getByFieldName('countryCode') || '';
    my $oCountry = Common::Country->new( search => $country );
    return $oCountry->alpha2 if $oCountry;

    return $self->handleError( "Unknown country code '$country'", RPS::DB::Item::SaleImportError::kErrorCountry );
}

sub mediaType {
    my $self = shift;

    my $mediaType = $self->_getByFieldName('mediaType') || '';
    if ( !$mediaType || $mediaType =~ /^audio$/i ) {
        return  RPS::DB::Item::MediaType::kMediaTypeAudio
    } elsif ( $mediaType =~ /^video$/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    }

    return $self->handleError( "Unknown media_type: '$mediaType'", RPS::DB::Item::SaleImportError::kErrorMediaType );
}

sub grossRevenue {
    my $self = shift;

    my $grossRevenue = $self->_getByFieldName('grossRevenue') || 0;

    return sprintf("%.8f", $grossRevenue);
}

sub _mapFaceProductType { }
sub _mapFaceServiceID   { 'serviceID' }
sub _mapFaceCountryCode { 'countryCode' }
sub _mapFaceFormatType  { 'formatType' }
sub _mapFaceMediaType   { 'mediaType' }

1;
