#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package RPS::Import::ProperUK::v5;

use strict;
use warnings;

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

use base 'RPS::Import::Importer';

sub _fieldMap {
    my $self = shift;

    my $version = $self->{version};

    my %field_map = (
        5 => {

            # Header
            dateBegin => 'B3',

            # Detail
            labelName       => 'A',
            countryCode     => 'I',
            productType     => 'B',
            artistName      => 'E',
            clientProductID => 'C',
            upc             => 'D',
            albumName       => 'F',
            currencyCode    => 'U',
            wholesalePrice  => 'G',
            sales           => 'J',
            salesRevenue    => 'L',
            returns         => 'M',
            returnsRevenue  => 'O',
            totalRevenue    => 'T',
            units           => 'P',
        },
        6 => {

            # Header
            dateBegin => 'B3',

            # Detail
            labelName        => 'A',
            countryCode      => 'I',
            productType      => 'B',
            artistName       => 'E',
            serviceProductID => 'C',
            upc              => 'D',
            albumName        => 'F',
            currencyCode     => 'U',
            wholesalePrice   => 'G',
            sales            => 'J',
            salesRevenue     => 'L',
            returns          => 'M',
            returnsRevenue   => 'O',
            totalRevenue     => 'T',
        },
        7 => {

            # Header
            dateBegin => 'B3',

            # Detail
            labelName        => 'A',
            countryCode      => 'J',
            productType      => 'B',
            artistName       => 'F',
            serviceProductID => 'D',
            upc              => 'E',
            albumName        => 'G',
            currencyCode     => 'X',
            wholesalePrice   => 'H',
            sales            => 'K',
            salesRevenue     => 'N',
            returns          => 'O',
            returnsRevenue   => 'R',
            units            => 'S',
            totalRevenue     => 'W',
            clientProductID  => 'D',
        },
        8 => {
            # Header
            dateBegin => 'B3',

            # Detail
            labelName       => 'A',
            countryCode     => 'J',
            productType     => 'B',
            artistName      => 'F',
            clientProductID => 'D',
            upc             => 'E',
            albumName       => 'G',
            currencyCode    => 'Y',
            wholesalePrice  => 'H',
            sales           => 'K',
            salesRevenue    => 'O',
            returns         => 'P',
            returnsRevenue  => 'T',
            units           => 'U',
            totalRevenue    => 'X',
        },
        11 => {

            # Header
            dateBegin => 'B3',

            # Detail
            labelName        => 'A',
            countryCode      => 'J',
            productType      => 'B',
            artistName       => 'F',
            clientProductID  => 'D',
            upc              => 'E',
            albumName        => 'G',
            currencyCode     => 'Y',
            wholesalePrice   => 'H',
            sales            => 'L',
            salesRevenue     => 'O',
            returns          => 'P',
            returnsRevenue   => 'S',
            units            => 'T',
            totalRevenue     => 'X',
        },
    );
    return $field_map{$version};
}

sub _unverifiedFieldMap {
    my $self = shift;
    my $version = $self->{version};

    my %fieldMap = (
        5 => {
            exchangeRate => 'S',
        },
        6 => {},
        7 => {},
        8 => {},
        11 => {
            exchangeRate => 'W',
        },
    );

    return $fieldMap{ $self->_version };
}

sub _headerIdentifier { 'upc' => 'Barcode' }

sub physical   { 1 }
sub channel    { RPS::File::Sale::CHANNEL_RETAIL }
sub priceLevel {
    return RPS::File::Sale::PLEVEL_FULL if $_[0]->version == 5;
    return RPS::File::Sale::PLEVEL_UNKNOWN;
}

sub upc {
    my $self = shift;
    my $upc  = $self->_getByFieldName('upc');
    return Common::Util::normalize_upc($upc) || '';
}

sub artistName {
    my $self = shift;
    my $name = $self->_getByFieldName('artistName');
    if ( $name =~ /(\w+)\s*,\s*(\w+)/ ) {
        return "$2 $1";
    }
    return $name;
}

sub serviceProductID {
    my $self = shift;
    my $id   = $self->_getByFieldName('serviceProductID') || '';
    $id =~ s/^'//;    # remove leading quote if present
    return $id;
}

sub clientProductID {
    my $self = shift;
    my $id = $self->_getByFieldName('clientProductID') || '';
    $id =~ s/^'//;
    return $id;
}

sub countryCode {
    my $self       = shift;
    my $country    = $self->_getByFieldName('countryCode');
    my %countryMap = ( 'UNITED KINGDOM' => 'GB', );
    $country = $countryMap{ uc $country } if ( exists $countryMap{ uc $country } );
    my $obj = Common::Country->Get($country);
    return $obj ? $obj->alpha2 : undef;
}

sub currencyCode {
    my $self  = shift;
    my $ccode = $self->_getByFieldName('currencyCode');
    return 'USD' if ( $ccode =~ /^us dollars$/i );
    return 'GBP' if ( $ccode =~ /^pounds sterling$/i );
    $self->fail("Unrecognized currency '$ccode'");
}

sub salesRevenue {
    my $self = shift;

    my $revenue      = $self->_getByFieldName('salesRevenue') || 0;
    my $exchangeRate = ($self->version =~ /^(?:5|11)$/ ? $self->_getByFieldName('exchangeRate') : 1);

    return $revenue * $exchangeRate;
}

sub returnsRevenue {
    my $self = shift;

    my $revenue      = $self->_getByFieldName('returnsRevenue') || 0;
    my $exchangeRate = ($self->version =~ /^(?:5|11)$/ ? $self->_getByFieldName('exchangeRate') : 1);

    return $revenue * $exchangeRate;
}

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

    if ( $productType =~ /^(?:cd|sacd)$/i ) {
        return RPS::File::Sale::TYPE_CD;
    } elsif ( $productType =~ /^(cdep|cdsi)$/i ) {
        return RPS::File::Sale::TYPE_CD_SIN;
    } elsif ( $productType =~ /^(lp2|lp|12x2|12)$/i ) {
        return RPS::File::Sale::TYPE_LP;
    } elsif ( $productType =~ /^12ep$/i ) {
        return RPS::File::Sale::TYPE_LP5;
    } elsif ( $productType =~ /^(cd2|cd3)$/i ) {
        return RPS::File::Sale::TYPE_DBL_CD;
    } elsif ( $productType =~ /^dvd$/i ) {
        return RPS::File::Sale::TYPE_DVD;
    }

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

sub _processSheet {
    my ($self, $sheet, $sheetnum) = @_;

    return $self->SUPER::_processSheet( $sheet, $sheetnum )
      if ( $self->{sheetname} =~ /^reported sales$/i );
}

sub _isValidSaleRecord {
    my $self    = shift;
    my $sales   = $self->_getByFieldName('sales')   || 0;
    my $returns = $self->_getByFieldName('returns') || 0;
    my $units   = $self->_getByFieldName('units')   || 0;

    my $isValid = ( $sales || $returns ) && ( $self->albumName || $self->upc );
    return unless $isValid;

    if ( ( $self->salesRevenue - $self->returnsRevenue ) && !$units ) {
        $self->fail( "Line " . $self->linenum . ": revenue with no units" );
    }

    if ( $self->_version == 7 && $sales - $returns != $units ) {
        $self->fail( "Line " . $self->linenum . ": Sales Units ($sales) - Return Units ($returns) does not = Net Units ($units)" );
    }

    return $isValid;
}

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