package RPS::Import::Sony::v46;

use strict;
use warnings;

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

use parent 'RPS::Import::ImporterMixed';

sub physical { 0 }

sub _fieldMapExtended {
    {
        digital => {
            option1 => {
                serviceID       => 'B',
                countryCode     => 'I',
                dateBegin       => 'K',
                dateEnd         => 'K',
                productType     => 'J',
                formatType      => 'L',
                clientProductID => 'C',
                artistName      => 'E',
                albumName       => 'D',
                isrc            => 'F',
                trackName       => 'G',
                units           => 'N',
                currencyCode    => 'A',
                price           => 'M',
                mediaType       => 'J',
            },
        }
    };
}

sub _unverifiedFieldMapExtended {
    {
        digital => {
            option1 => {
                _distFee => 'K',
            },
        }
    };
};

sub _headerIdentifierExtended {
    {
        digital => {
            option1 => {
                productType => 'Product Configuration',
            },
        }
    };
}

my %mapProductMedia = (
    '95 - digital audio longplay' => {
        product_type => RPS::File::Sale::TYPE_ALBUM,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'c1 - digital combo longplay' => {
        product_type => RPS::File::Sale::TYPE_ALBUM,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'c9 - digital video longform' => {
        product_type => RPS::File::Sale::TYPE_ALBUM,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeVideo,
    },
    '91 - digital audio track' => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'b5 - digital video track' => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeVideo,
    },
    'd5 - digital audio snippet' => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'r3 - mastertone' => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'r5 - ringback tone' => {
        product_type => RPS::File::Sale::TYPE_TRACK,
        media_type   => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
);

my %mapFormat = (
    'bonus - mobile stream - paid subscription' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'bonus - online stream - ad supported' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'bonus - online stream - paid subscription' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'bonus - mobile stream - ad supported' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'bonus- mobile tethered' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'bonus- online tethered' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'ephemeral' => {
        format_type => RPS::File::Sale::FORMAT_EPHEMERAL,
    },
    'jukebox' => {
        format_type => RPS::File::Sale::FORMAT_JUKEBOX,
    },
    'kiosk' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'locker' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'locker streaming' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'mobile ephemeral' => {
        format_type => RPS::File::Sale::FORMAT_EPHEMERAL,
    },
    'mobile stream (ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'mobile stream (non-ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'mobile tethered (ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'mobile tethered (non-ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'mobile webcasting' => {
        format_type => RPS::File::Sale::FORMAT_NON_EPHEMERAL,
    },
    'multi-platform permanent download' => {
        format_type => RPS::File::Sale::FORMAT_DOWNLOAD,
    },
    'multi-platform stream (ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'multi-platform stream (non-ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'online audio track broadcast webcasting' => {
        format_type => RPS::File::Sale::FORMAT_NON_EPHEMERAL,
    },
    'online permanent download' => {
        format_type => RPS::File::Sale::FORMAT_DOWNLOAD,
    },
    'online stream (ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'online stream (non-ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    },
    'online subscription download' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'online tethered' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'online tethered (non-ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'online tethered (ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_TETHERED,
    },
    'settlement - ephemeral' => {
        format_type => RPS::File::Sale::FORMAT_EPHEMERAL,
    },
    'settlement - webcasting' => {
        format_type => RPS::File::Sale::FORMAT_NON_EPHEMERAL,
    },
    'settlement-stream(ad supported)' => {
        format_type => RPS::File::Sale::FORMAT_STREAM,
    }
);

sub saleDates {
    my $self = shift;

    # YYYYH\d
    my $dateBegin = $self->_getByFieldName('dateBegin') || '';
    if ( $dateBegin =~ /^(\d{4})H([1-2])$/i ) {
        my ($m, $d) = $2 == 1 ? (6, 30) : (12, 31) ;
        return
            sprintf("%04d-%02d-%02d", $1, $m, 1),
            sprintf("%04d-%02d-%02d", $1, $m, $d);
    }
    # 2H19 - (December 2019)
    elsif ( $dateBegin =~ /^([1-2])H(\d{2})$/i ) {
        my ($m, $d) = $1 == 1 ? (6, 30) : (12, 31) ;
        return
            sprintf("%04d-%02d-%02d", "20$2", $m, 1),
            sprintf("%04d-%02d-%02d", "20$2", $m, $d);
    }

    return $self->fail("Unable to determine date from: '$dateBegin'." );
}

sub serviceID {
    my $self = shift;

    my $service = lc( $self->_getByFieldName('serviceID') || '' );
    $service =~ s/(.+)\(.*\|.*\)$/$1/;
    my $serviceID = $self->getServiceID($service) || $RPS::Import::ServiceMap::SERVICE_ALIASES{$service} || $self->_getServiceID($service);
    return $serviceID if $serviceID;

    $self->fail("Can't determine service_id from: $service");
}

sub _getServiceID {
    my ($self, $service) = @_;

    return Client::Service::DSP_7DIGITAL               if $service =~ /^7 digital/i;
    return Client::Service::DSP_NINESQUARED            if $service =~ /^9squared/i;
    return Client::Service::DSP_ACOUSTIC_SOUNDS_INC    if $service =~ /^acoustic sounds/i;
    return Client::Service::DSP_AMAZON                 if $service =~ /^amazon/i;
    return Client::Service::DSP_AMI                    if $service =~ /^ami/i;
    return Client::Service::DSP_APPLE_MUSIC            if $service =~ /^apple/i;
    return Client::Service::DSP_CATCH_MEDIA            if $service =~ /^catch\s?media/i;
    return Client::Service::DSP_DEEZER                 if $service =~ /^deezer/i;
    return Client::Service::DSP_FACEBOOK               if $service =~ /^facebook/i;
    return Client::Service::DSP_FLYWHEEL               if $service =~ /^flywheel/i;
    return Client::Service::DSP_FRESHPLANET            if $service =~ /^freshplanet/i;
    return Client::Service::DSP_GOOGLE                 if $service =~ /^google/i;
    return Client::Service::DSP_GRAYV                  if $service =~ /^gray v/i;
    return Client::Service::DSP_HDTRACKS               if $service =~ /^hdtracks/i;
    return Client::Service::DSP_IHEARTRADIO            if $service =~ /^iheartradio/i;
    return Client::Service::DSP_KEEFE_GROUP            if $service =~ /^keefe group/i;
    return Client::Service::DSP_LIBRARYIDEAS           if $service =~ /^library ideas/i;
    return Client::Service::DSP_MANAGED_MEDIA          if $service =~ /^managed media/i;
    return Client::Service::DSP_MEDIANET               if $service =~ /^medianet/i;
    return Client::Service::DSP_NAPSTER                if $service =~ /^napster/i;
    return Client::Service::DSP_NEUROTICMEDIA          if $service =~ /^neurotic/i;
    return Client::Service::DSP_ORCHARD                if $service =~ /^(?:the\s?)?orchard/i;
    return Client::Service::DSP_PANDORA                if $service =~ /^pandora/i;
    return Client::Service::DSP_PCMTECHNOLOGIES        if $service =~ /^pcm technologies/i;
    return Client::Service::DSP_PELOTON                if $service =~ /^peloton/i;
    return Client::Service::DSP_PLAYNETWORK            if $service =~ /^playnetwork/i;
    return Client::Service::DSP_QELLO_LLC              if $service =~ /^qello/i;
    return Client::Service::DSP_REAL                   if $service =~ /^rhapsody/i;
    return Client::Service::DSP_SCREENPLAY_INC         if $service =~ /^screenplay/i;
    return Client::Service::DSP_SECURE_MEDIA           if $service =~ /^secure media/i;
    return Client::Service::DSP_SLACKERINC             if $service =~ /^slacker/i;
    return Client::Service::DSP_SOUNDEXCHANGE          if $service =~ /^sound exchange/i;
    return Client::Service::DSP_SOUNDCLOUD             if $service =~ /^soundcloud/i;
    return Client::Service::DSP_SOUNDEXCHANGE          if $service =~ /^soundexchange/i;
    return Client::Service::DSP_SOUNDTRACK_YOUR_BRAND  if $service =~ /^soundtrack your brand/i;
    return Client::Service::DSP_SPOTIFY                if $service =~ /^spotify/i;
    return Client::Service::DSP_TMOBILE                if $service =~ /^t-mobile/i;
    return Client::Service::DSP_TIDAL                  if $service =~ /^tidal/i;
    return Client::Service::DSP_TIKTOK                 if $service =~ /^tiktok/i;
    return Client::Service::DSP_TOUCHTUNES             if $service =~ /^touchtunes/i;
    return Client::Service::DSP_TRANSWORLD_ENT         if $service =~ /^trans world entertainment/i;
    return Client::Service::DSP_VERIZON                if $service =~ /^verizon/i;
    return Client::Service::DSP_VERVELIFE              if $service =~ /^vervelife/i;
    return Client::Service::DSP_VEVO                   if $service =~ /^vevo/i;
    return Client::Service::DSP_WEYV                   if $service =~ /^weyv/i;
    return Client::Service::DSP_WIMP                   if $service =~ /^wimp/i;
    return Client::Service::DSP_YOUTUBE                if $service =~ /^youtube/i;
    return Client::Service::DSP_AAPTIV                 if $service =~ /^aaptiv/i;
    return Client::Service::DSP_DELTA_AIR_LINES        if $service =~ /^delta air lines/i;
    return Client::Service::DSP_RADIONOMY              if $service =~ /^radionomy/i;
    return Client::Service::DSP_BOKU                   if $service =~ /^boku/i;
    return Client::Service::DSP_MUSIC_AFICIONADO       if $service =~ /^music aficionado/i;

    if ($service =~ /^(?:coin-operated|limited non|non coin|pou4|ppy|pq|pr|subscription radio|sx\s?-|uk student|web fulfillment)/) {
        return Client::Service::DSP_SONY;
    }

    return;
}

sub countryCode {
    my $self = shift;

    my $countryCode = lc( $self->_getByFieldName('countryCode') || '' );
    $countryCode =~ s/^(\w{3}).*/$1/;

    my $obj = Common::Country->Get($countryCode);
    return $obj->alpha2 if $obj;

    $self->fail("Can't determine country_code from: $countryCode");

}

sub productType {
    my $self = shift;

    my $type = lc( $self->_getByFieldName('productType') || '' );
    if ( exists $mapProductMedia{$type} ) {
        return $mapProductMedia{$type}{product_type};
    }

    $self->fail("Can't determine product_type from: $type");
}

sub formatType {
    my $self = shift;

    my $type = lc( $self->_getByFieldName('formatType') || '' );
    if ( exists $mapFormat{$type} ) {
        return $mapFormat{$type}{format_type};
    }

    if ( $type =~ /^mobile (?:permanent download|subscription permanent)$/ ) {
        return $self->_getByFieldName('productType') =~ /^(?:R3 - Mastertone|R5 - Ringback Tone)$/i
            ? RPS::File::Sale::FORMAT_RINGTONE
            : RPS::File::Sale::FORMAT_DOWNLOAD;
    }

    $self->fail("Can't determine format_type from: $type");
}

sub mediaType {
    my $self = shift;

    my $type = lc( $self->_getByFieldName('mediaType') || '' );
    if ( exists $mapProductMedia{$type} ) {
        return $mapProductMedia{$type}{media_type};
    }

    $self->fail("Can't determine media_type from: $type");
}

sub currencyCode {
    my $self = shift;

    my $code = $self->_getByFieldName('currencyCode') || '';
    return 'USD' if $code =~ /^US Dollar$/;

    $self->fail("Can't determine currency_code from: $code");
}

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

sub _isValidSaleRecord {
    my $self = shift;

    return 1 if $self->_getByFieldName('dateBegin') && ($self->price || $self->units);
    return;
}


1;