package RPS::Import::Orchard::v30;

use strict;
use warnings;

use lib '/app/tools/rps/lib';

use RPS::Import::ServiceMap;
use RPS::Import::OrchardPub2;

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

sub physical { 2 }

sub _fieldMapExtended {
    {
        mixed => {
            option1 => {
                labelName        => 'H',
                serviceID        => 'C',
                countryCode      => 'D',
                dateBegin        => 'B',
                productType      => 'P',
                formatType       => 'O',
                serviceProductID => 'F',
                clientProductID  => 'G',
                artistName       => 'I',
                upc              => 'F',
                albumName        => 'J',
                isrc             => 'L',
                trackNum         => 'N',
                trackName        => 'K',
                units            => 'T',
                currencyCode     => 'AB',
                wholesalePrice   => 'R',
                totalRevenue     => 'AA',
                price            => 'AA',
                mediaType        => 'Q',
                grossRevenue     => 'U',
            },
        }
    }
}

sub _unverifiedFieldMapExtended {
    {
        mixed => {
            option1 => {
                _digitalProductType => 'E',
            },
        }
    };
}

sub _headerIdentifierExtended {
    {
        mixed => {
            option1 => {
                formatType => 'Trans Type',
            },
        }
    };
}

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

my $ORCHARD_PUB2_FORMAT_MAP = RPS::Import::OrchardPub2::get_format_map();

sub serviceID {
    my $self = shift;

    if ( !$self->isDigitalProduct( $self->productType ) ) {
        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 countryCode {
    my $self = shift;

    my $name = $self->_getByFieldName('countryCode') || 'US';

    my $country = Common::Country->Get($name);
    return $country->alpha2 if ($country && $country->alpha2);

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

sub saleDates {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin') || '';
    # YYYY-MM-DD
    if ( $dateBegin =~ /^(\d{4}).?(\d{2}).?(\d{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 dates from: '$dateBegin'");
}

sub productType {
    my $self = shift;

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

    # physical
    if ( $formatType =~ /^(?:PS|RS|LP|LR|MP|MR|OP|OR|TP|TR|PM|PH|PS|RE)$/i ) {
        return RPS::File::Sale::TYPE_CD if $type =~ /^CD$/i;
        return RPS::File::Sale::TYPE_CD if $type =~ /^Book$/i;
        return RPS::File::Sale::TYPE_DVD if $type =~ /^DVD$/i;
        return RPS::File::Sale::TYPE_LP if $type =~ /^(?:LP|"?12""? Vinyl"?)$/i;
        return RPS::File::Sale::TYPE_LP5 if $type =~ /^LP SINGLE$/i;
        return RPS::File::Sale::TYPE_LP5 if $type =~ /^"?7""? Vinyl"?$/i;
        return RPS::File::Sale::TYPE_LP if $type =~ /^"?10""? Vinyl"?$/i;
        return RPS::File::Sale::TYPE_CASS if $type =~ /^CASS$/i;
        return RPS::File::Sale::TYPE_CASS if $type =~ /^Cassette$/i;
        return RPS::File::Sale::TYPE_BLURAY if $type =~ /^Blu-ray$/i;
        $self->fail("Unknown physical product type: '$type'");
    }

    # digital
    return RPS::File::Sale::TYPE_TRACK if $typeDigital =~ /^Track$/i;
    return RPS::File::Sale::TYPE_ALBUM if $typeDigital =~ /^Album$/i;

    $self->fail("Cannot determine product type from: digital '$typeDigital' or physical '$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 =~ /^(?:AS|AV|CL|MT|MV|S|SV|VA|SB|NS|AP|YP|EQ|DB|FS)$/i ) {
        return RPS::File::Sale::FORMAT_STREAM;
    } elsif ( $type =~ /^(?:TD|TA|VR)$/i ) {
        return RPS::File::Sale::FORMAT_TETHERED;
    } elsif ( $type =~ /^(?:NR|NT)$/i ) {
        return RPS::File::Sale::FORMAT_PERFORMANCE;
    } elsif ( $type =~ /^(?:RB|DR)$/i ) {
        return RPS::File::Sale::FORMAT_RINGTONE;
    } elsif ( $type =~ /^(?:UA|UT|UV)$/i ) {
        return RPS::File::Sale::FORMAT_DOWNLOADUPGRADE;
    }

    # fallback to OrchardPub2 mapping
    if (exists $ORCHARD_PUB2_FORMAT_MAP->{uc $type}) {
        my $orchard_pub2_mapping = $ORCHARD_PUB2_FORMAT_MAP->{uc $type};
        return $orchard_pub2_mapping->{format_type} if $orchard_pub2_mapping->{format_type};
    }

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

sub mediaType {
    my $self = shift;

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

    return RPS::DB::Item::MediaType::kMediaTypeAudio if $type =~ /^A$/i;
    return RPS::DB::Item::MediaType::kMediaTypeVideo if $type =~ /^V$/i;

    # fallback to OrchardPub2 mapping using formatType
    my $formatType = $self->_getByFieldName('formatType') || '';
    if (exists $ORCHARD_PUB2_FORMAT_MAP->{uc $formatType}) {
        my $orchard_pub2_mapping = $ORCHARD_PUB2_FORMAT_MAP->{uc $formatType};
        return $orchard_pub2_mapping->{media_type} if $orchard_pub2_mapping->{media_type};
    }

    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;

    $units =~ s/,//g;

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

    return $units;
}

sub serviceProductID {
    my $self = shift;

    if ( RPS::Import::Importer->isDigitalProduct( $self->productType() ) ) {
        return $self->_getByFieldName('serviceProductID');
    } else {
        return undef;
    }
}

# physical
sub netUnits       { $_[0]->_getByFieldName('units')                  || 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;
}

sub _isValidSaleRecord {
    my $self = shift;

    # see RSD-12242
    return 1 if ($self->price || $self->totalRevenue)
        || ($self->units || $self->netUnits);

    return 0;
}

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

1;
