package RPS::Import::FatBeats::v4;

use strict;
use warnings;

use lib '/app/tools/rps/lib';
use base 'RPS::Import::ImporterMixed';

sub physical { 1 }

sub _fieldMapExtended {
    {
        physical => {
            option1 => {
                countryCode     => 'I',
                dateBegin       => 'E',
                productType     => 'C',
                clientProductID => 'B',
                artistName      => 'C',
                upc             => 'F',
                albumName       => 'C',
                retailPrice     => 'J',
                totalRevenue    => 'P',
            },
        },
    };
}

sub _unverifiedFieldMapExtended {
    {
        physical => {
            option1 => {
                _itemGroup       => 'A',
                _netUnits        => 'K',
                _itemDescription => 'C',
            },
        }
    };
}

sub _headerIdentifierExtended {
    {
        physical => {
            option1 => {
                productType => 'Description',
            },
        },
    };
}

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 %productMappings = (
    "cd"                => RPS::File::Sale::TYPE_CD,
    "cd boxset"         => RPS::File::Sale::TYPE_CD,
    "ep"                => RPS::File::Sale::TYPE_LP,
    "lp"                => RPS::File::Sale::TYPE_LP,
    "splatter vinyl ep" => RPS::File::Sale::TYPE_LP,
    "6x7'' box set"     => RPS::File::Sale::TYPE_LP,
    "picture disc ep"   => RPS::File::Sale::TYPE_LP,
    "2xlp w\/ poster"   => RPS::File::Sale::TYPE_LP,
    "red vinyl 2xlp"    => RPS::File::Sale::TYPE_LP,
    "7\""               => RPS::File::Sale::TYPE_LP5,
    "12\""              => RPS::File::Sale::TYPE_LP5,
    "2xlp"              => RPS::File::Sale::TYPE_LP5,
    "10\" vinyl ep"     => RPS::File::Sale::TYPE_LP5,
    "2xlp white vinyl"  => RPS::File::Sale::TYPE_LP5,
    "10'' vinyl ep"     => RPS::File::Sale::TYPE_LP5,
    "2xcd"              => RPS::File::Sale::TYPE_DBL_CD,
);

sub serviceID    { Client::Service::DSP_FAT_BEATS }
sub currencyCode { 'USD' }
sub channel      { RPS::File::Sale::CHANNEL_RETAIL }
sub priceLevel   { RPS::File::Sale::PLEVEL_UNKNOWN }
sub mediaType    { RPS::DB::Item::MediaType::kMediaTypeAudio }

sub saleDates {
    my $self = shift;

    # 09 May 2023
    my $dateBegin = $self->_getByFieldName('dateBegin') || '';
    if ( $dateBegin =~ /^(\d{1,2}) (\w{3,9}) (\d{4})$/ ) {
        my $month = substr(lc($2), 0, 3);
        return $self->_getDates(
            date_begin => sprintf( "%04d-%02d-%02d", $3, $months{$month}, $1 )
        );
    }
    # MM/DD/YYYY
    elsif ( $dateBegin =~ /^(\d{1,2})[\/](\d{2})[\/](\d{4})$/ ) {
        return $self->_getDates(
            date_begin => sprintf( "%04d-%02d-%02d", $3, $1, $2 )
        );
    }

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

sub countryCode {
    my $self = shift;

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

    $self->fail("Unable to determine country code from: '$name'");
}

sub clientProductID {
    my $self= shift;

    my $clientProductID = $self->_getByFieldName('clientProductID') || $self->{__clientProductID};
    if ( $clientProductID && $clientProductID ne ( $self->{__clientProductID} || '' ) ) {
        $self->{__clientProductID} = $clientProductID;
    }

    return $clientProductID;
}

sub productType {
    my $self = shift;

    my $type = $self->_getFromItemDescription('productType') || '';
    if ( exists $productMappings{lc $type} ) {
        return $productMappings{lc $type};
    }

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

sub artistName {
    my $self= shift;

    my $artistName = $self->_getFromItemDescription('artistName') || '';
    return $artistName;
}

sub albumName {
    my $self = shift;

    my $albumName = $self->_getFromItemDescription('albumName') || '';
    return $albumName;
}

sub _getFromItemDescription {
    my ($self, $type) = @_;

    # example: "GrandeMarshall - Risk/Reward (CD)" OR "Fool's Gold Presents: Night Shift (CD)"
    my $value = $self->_getByFieldName('_itemDescription') || '';
    return $self->{_cache}{$type} unless $value;

    my @parts = split /\s+-\s+/, $value;
    unshift @parts, '' if @parts == 1;
    @parts[1,2] = $parts[1] =~ /^(.+)\s?\((.+)\)$/;
    foreach (@parts) {
        $_ =~ s/^\s+|\s+$//g;
        @{ $self->{_cache} }{ qw/artistName albumName productType/ } = @parts;
    }

    return $self->{_cache}{$type};
}

# physical
sub netUnits {
    my $self = shift;

    my $units   = $self->_getByFieldName('_netUnits') || 0;
    my $revenue = $self->totalRevenue;

    if ( $revenue > 0 ) {
        return abs $units;
    } elsif ( $revenue < 0 ) {
       return abs($units) * -1
    }

    return $units;
}
sub totalRevenue       { $_[0]->_getByFieldName('totalRevenue') || 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 _isValidSaleRecord {
    my $self = shift;

    my $itemGroup = $self->_getByFieldName('_itemGroup') || '';
    return 0 if $itemGroup =~ /^Total$/i;
    return 0 if !$self->_getByFieldName('_netUnits') && !$self->_getByFieldName('totalRevenue');

    return 1;
}


1;
