#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2013 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package RPS::Import::ADA::v17;

use strict;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::UTF8;

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

use base 'RPS::Import::MapFaceBase';
use base 'RPS::Import::ADA::ADACommon';

sub _fieldMap {
    {
        labelName        => 'N',
        dateBegin        => 'T',
        productType      => 'H',
        serviceProductID => 'S',
        artistName       => 'E',
        upc              => 'O',
        isrc             => 'G',
        albumName        => 'F',
        trackName        => 'F',
        price            => 'K',
        units            => 'J',
        countryCode      => 'D',
        serviceID        => 'C',
    };
}

sub _unverifiedFieldMap {
    { mediaCode => 'B', };
}

sub _headerIdentifier { ( dateBegin => 'TRANSACTION_DATE' ) }

sub currencyCode { 'USD' }

sub serviceID {
    my $self = shift;

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

    if ( $self->countryCode && $self->countryCode eq 'KR' ) {

        # FB16136: Anything coming out of Korea is mapped to ADA
        #

        #        print STDERR "D: detected Korean wide character service name, defaulting to ADA\n";
        $serviceID = Client::Service::DSP_ADA;
    }

    if ( !$serviceID ) {

        # Apply ADA-specific service mappings, if any (FB33)
        #
        if (   $service =~ /^\(\?\)\?\?\?\?\?$/
            || $service =~ /^mlj inc.$/i ) {
            $serviceID = Client::Service::DSP_ADA;
        }

        # Otherwise try the normal serviceID lookups
        #
        else {
            $serviceID = $self->getServiceID( lc($service) ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };
        }
    }

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

sub _normalizeValue {
    my $self  = shift;
    my $value = shift;
    $value =~ s/=//;
    $value =~ s/"//g;
    return $value;
}

sub unitPrice { abs( shift->SUPER::unitPrice ) }
sub price     { abs( shift->SUPER::price ) }

sub units {
    my $self = shift;

    # Implementing https://royaltyshare.fogbugz.com/default.asp?W21
    if ( $self->rPrice < 0 ) { return 0 - abs( $self->rUnits ); }
    return abs( $self->rUnits );
}

sub isrc {
    my $self = shift;
    my $isrc = $self->_getByFieldName('isrc') || return;
    return $self->_normalizeValue($isrc);
}

sub upc {
    my $self = shift;
    my $upc = $self->_getByFieldName('upc') || return;
    return $self->_normalizeValue($upc);
}

sub serviceProductID {
    my $self = shift;
    my $serviceProductID = $self->_getByFieldName('serviceProductID') || return;
    return $self->_normalizeValue($serviceProductID);
}

sub saleDates {
    my $self = shift;

    my $dateBegin;
    my $dateEnd;

    my $startDate = $self->_getDateBegin();
    my $endDate   = $self->_getDateEnd();

    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
    );

    my ( $day, $monthName, $year ) = $startDate =~ m/(\d{1,2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2})/i;
    my $month = $months{ lc $monthName };

    if ( $monthName && $year ) {
        my $_startDate = sprintf( "%04d-%02d-%02d", $year + 2000, $month, 1 );
        ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $_startDate );
    }

    return ( $dateBegin, $dateEnd );
}

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

    if ( $type =~ /^isrc$/i ) {
        return RPS::File::Sale::TYPE_TRACK;
    } elsif ( $type =~ /^upc$/i ) {
        return RPS::File::Sale::TYPE_ALBUM;
    } else {
        return $type;
    }
}

sub albumName {
    my $self = shift;
    my $name = $self->_getByFieldName('albumName');
    my $isrc = $self->_getByFieldName('isrc');
    $isrc = $self->_normalizeValue($isrc);

    # If the value in the ISRC column is actually a UPC,
    # then we know this is an album.
    if ( $isrc && $isrc =~ /^\d/ ) {
        return $name;
    }
}

sub trackName {
    my $self = shift;
    my $name = $self->_getByFieldName('trackName');
    my $isrc = $self->_getByFieldName('isrc');
    $isrc = $self->_normalizeValue($isrc);

    # If the value in the ISRC column is actually an ISRC (and not a UPC),
    # then we know this is a track.
    if ( $isrc && $isrc =~ /^\w/ ) {
        return $name;
    }
}

sub formatType {
    my $self      = shift;
    my $mediaCode = $self->_getByFieldName('mediaCode');
    if ( $mediaCode =~ /^(emdtrack|evd|emdalbum)$/i ) {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    } elsif ( $mediaCode =~ /^(emd(album|track)?streaming|evdstreaming)$/i ) {
        return RPS::File::Sale::FORMAT_STREAM;
    } elsif ( $mediaCode =~ /^(eringback)$/i ) {
        return RPS::File::Sale::FORMAT_RINGTONE;
    } else {
        return $mediaCode;
    }
}

sub mediaType {
    my $self      = shift;
    my $mediaCode = $self->_getByFieldName('mediaCode');
    if ( $mediaCode =~ /^(emd(track|album)?(streaming)?|evdstreaming|eringback)$/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    } elsif ( $mediaCode =~ /^evd$/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    } else {
        return $mediaCode;
    }
}

## MapFace Stuff
sub _mapFaceCompatibleVersions {
    return ( 17, 18, 19, 23, 24, 25, 26, 27, 28 );
}

sub _mapFaceServiceID {
    return ( 'serviceID', 'countryCode' );
}

sub _mapFaceCountryCode {
    return ('countryCode');
}

sub _mapFaceProductType {
    return ('productType');
}

sub _mapFaceFormatType {
    return ('mediaCode');
}

sub _mapFaceMediaType {
    return ('mediaCode');
}

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