package RPS::Import::Orchard::v29;

use strict;
use warnings;

use lib '/app/tools/rps/lib';
use RPS::Import::ServiceMap;
use Date::Calc qw(Days_in_Month Decode_Month);

use parent qw/RPS::Import::MapFaceBase RPS::Import::ImporterMixed/;

sub physical { 2 }

sub _fieldMapExtended {
    {
        mixed => {
            option1 => {
                serviceID        => 'F',
                countryCode      => 'G',
                dateBegin        => 'E',
                productType      => 'R',
                formatType       => 'R',
                clientProductID  => 'K',
                artistName       => 'M',
                albumName        => 'N',
                isrc             => 'Q',
                trackName        => 'O',
                units            => 'V',
                currencyCode     => 'AA',
                wholesalePrice   => 'T',
                totalRevenue     => 'Z',
                price            => 'Z',
                mediaType        => 'R',
            },
        }
    }
}

sub _unverifiedFieldMapExtended {
    {
        mixed => {
            option1 => {
                _orchardUPC       => 'H',
                _manufactererUPC  => 'I',
                _netUnits         => 'V',
            },
        }
    };
}

sub _headerIdentifierExtended {
    {
        mixed => {
            option1 => {
                artistName => 'RELEASE_ARTIST',
            },
        }
    };
}


sub channel    { RPS::File::Sale::CHANNEL_RETAIL }
sub priceLevel { RPS::File::Sale::PLEVEL_UNKNOWN }

sub serviceID {
    my $self = shift;

    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 countryCode {
    my $self = shift;

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

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

sub saleDates {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin') || '';
    # MM/DD/YYYY
    if ( $dateBegin =~ /^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/ ) {
        my $y = substr($3, -2);
        my $date = sprintf "20%02d-%02d-%02d", $y, $1, $2;
        return $self->SUPER::_getDates( date_begin => $date );
    }
    # YYYY-MM-DD
    elsif ( $dateBegin =~ /^(\d{2,4})\-(\d{1,2})\-(\d{1,2})$/ ) {
        my $y = substr($1, -2);
        my $date = sprintf "20%02d-%02d-%02d", $y, $2, $3;
        return $self->SUPER::_getDates( date_begin => $date );
    }

    $self->fail("Unable to determine start/end dates from: '$dateBegin'");
}

sub upc {
    my $self = shift;

    my $orchardUPC = $self->_getByFieldName('_orchardUPC')      || '';
    my $manufUPC   = $self->_getByFieldName('_manufactererUPC') || '';

    if ( $self->isDigitalProduct( $self->productType ) ) {
        return $orchardUPC;
    }

    return $manufUPC || $orchardUPC;
}

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('productType') || '';

    # physical
    if ( $type =~ /^(?:PS|RE|LP|LR|MP|MR|OP|OR|TP|TR)$/i ) {
        return RPS::File::Sale::TYPE_CD;
    }

    # digital
    if ( $type =~ /^(?:SV|AV|VA|AS|S|MT|CL|DT|FA|NR|FS|NS|SF|DV|DJ|TD|RB|SC|DR|AC|AEA|AEV|AO|AP|CC|CE|
                       CR|DB|EH|ER|MA|MD|ME|MV|NT|PA|PF|PP|PV|RC|RL|RR|RW|SL|SR|TL|TV|UN|UP|US|
                       UT|UV|VS|VU|WA|WS|YP|SA|)$/ix ) {
        return RPS::File::Sale::TYPE_TRACK;
    } elsif ( $type =~ /^(?:DA|EQ|SB|TA|UA|VR)$/i ) {
        return RPS::File::Sale::TYPE_ALBUM;
    }

    $self->fail( "Unable to determine product_type from: '$type'" );

}

sub formatType {
    my $self = shift;

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

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

    if ( $type =~ /^(?:DT|DA|DV)$/i ) {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    } elsif ( $type =~ /^(?:SV|AV|VA|AS|S|MT|CL|FA|FS|SF|DJ|AC|AEA|AEV|AO|AP|CE|CR|DB|EQ|ME|MV|PF|SB|TL|US|VS|VU|WA|WS|YP|SA)$/i ) {
        return RPS::File::Sale::FORMAT_STREAM;
    } elsif ( $type =~ /^(?:TD|TA|VR)$/i ) {
        return RPS::File::Sale::FORMAT_TETHERED;
    } elsif ( $type =~ /^(?:NR|NS|CC|EH|ER|MA|MD|NT|PA|PP|PV|RC|RL|RR|RW|SL|TV|UN|UP)$/i ) {
        return RPS::File::Sale::FORMAT_PERFORMANCE;
    } elsif ( $type =~ /^(?:RB|DR)$/i ) {
        return RPS::File::Sale::FORMAT_RINGTONE;
    } elsif ( $type =~ /^(?:SC|SR)$/i ) {
        return RPS::File::Sale::FORMAT_SYNC;
    } elsif ( $type =~ /^(?:UA|UT|UV)$/i ) {
        return RPS::File::Sale::FORMAT_DOWNLOADUPGRADE;
    }

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

sub mediaType {
    my $self = shift;

    my $type = $self->_getByFieldName('mediaType') || '';

    if ( $type =~ /^(?:AS|S|MT|CL|DT|FA|NR|FS|NS|DA|DJ|TD|RB|SC|DR|PS|RE|AEA|AP|DB|EQ|ME|PF|SB|US|WA|WS|SA|TA|UA|
                    UT|CC|EH|ER|MA|MD|NT|PA|PP|PV|RC|RL|RR|RW|SL|TV|UN|UP|SR|LP|LR|MP|MR|OP|OR|TP|TR)$/ix ) {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    } elsif ( $type =~ /^(?:SV|AV|VA|SF|DV|AC|AEV|AO|CE|CR|MV|TL|VS|VU|YP|VR|UV)$/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    }

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

# digital
sub price     { abs( shift->_getByFieldName('price') || 0 ) }
sub unitPrice { abs shift->SUPER::unitPrice }
sub units     {
    my $self = shift;

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

    if ( $price > 0 ) {
        $units = $units ? abs($units) : 1;
    } elsif ( $price < 0 ) {
        $units = $units ? -1 * abs($units) : -1;
    }

    return $units;
}

# physical
sub netUnits       { $_[0]->_getByFieldName('_netUnits')              || 0 }
sub sales          { $_[0]->netUnits     > 0 ? $_[0]->netUnits         : 0 }
sub salesRevenue   { $_[0]->totalRevenue > 0 ? $_[0]->totalRevenue     : 0 }
sub returns        { $_[0]->netUnits     < 0 ? abs $_[0]->netUnits     : 0 }
sub returnsRevenue { $_[0]->totalRevenue < 0 ? abs $_[0]->totalRevenue : 0 }
sub totalRevenue {
    my $self = shift;
    my $revenue = $self->_getByFieldName('totalRevenue') || 0;
    return $revenue;
}

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


1;
