#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2013 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package RPS::Import::Sony::v11;

use strict;

use Date::Calc qw(Days_in_Month);

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::UTF8;
use Common::Country;

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

sub _fieldMap {
    {
        # header
        #
        labelName        => 'A',  # A6
        dateBegin        => 'F',  # F3

        # detail
        #
        artistName       => 'C',
        productType      => 'D',
        formatType       => 'I',
        countryCode      => 'H',
        units            => 'L',
        price            => 'Q',

        albumName        => 'B',
        trackName        => 'B',

        upc              => 'A',
        isrc             => 'A',
    }
}

sub _headerIdentifier {
    ( 'upc' => 'Product Number' )
}

sub currencyCode { 'AUD' }

sub saleDates {
    my $self = shift;
    return ($self->{_startDate}, $self->{_endDate}) if( $self->{_startDate} ); # from header of current sheet; see _processSheet
}

sub labelName {
    my $self = shift;
    return $self->{_labelName} if( $self->{_labelName} ); # from header of current sheet; see _processSheet
}

sub countryCode {
    my $self = shift;
    my $name = $self->_getByFieldName('countryCode');
    
    if( $name )
    {
        my $o = Common::Country->Get( $name );
        return $o->alpha2() if( $o );
    }

    return $name;  # Return original name and let MapFace deal with it
}

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

    if( $config =~ /^digital (audio|video) track$/i || $config =~ /^mastertone$/i )
    {
        return RPS::File::Sale::TYPE_TRACK;
    }
    elsif( $config =~ /^digital audio longplay$/i || $config =~ /^digital video longform$/i )
    {
        return RPS::File::Sale::TYPE_ALBUM;
    }

    return $self->handleError("Unknown config: $config", RPS::DB::Item::SaleImportError::kErrorProductType );
}

my %formatMediaMap = (
    'digital audio track' => {
        '(cds|dls)' => {
            format => RPS::File::Sale::FORMAT_STREAM,
            media  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        '(dbl|ddd|dol|dts|dbt)' => {
            format => RPS::File::Sale::FORMAT_DOWNLOAD,
            media  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
    },
    'digital audio longplay' => {
        '(dol|dts)' => {
            format => RPS::File::Sale::FORMAT_DOWNLOAD,
            media  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        '(ddd|dbl|dbt)' => {
            format => RPS::File::Sale::FORMAT_DOWNLOAD,
            media  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
    },
    'digital video track' => {
        '(cds|dls)' => {
            format => RPS::File::Sale::FORMAT_STREAM,
            media  => RPS::DB::Item::MediaType::kMediaTypeVideo,
        },
        'dol' => {
            format => RPS::File::Sale::FORMAT_DOWNLOAD,
            media  => RPS::DB::Item::MediaType::kMediaTypeVideo,
        },
    },
    'digital video longform' => {
        'dol' => {
            format => RPS::File::Sale::FORMAT_DOWNLOAD,
            media  => RPS::DB::Item::MediaType::kMediaTypeVideo,
        },
    },
    'mastertone' => {
        'cds' => {
            format => RPS::File::Sale::FORMAT_STREAM,
            media  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        '(dts|dol)' => {
            format => RPS::File::Sale::FORMAT_RINGTONE,
            media  => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
    },
);

sub _getFormatMedia {
    my $self = shift;
    my $config = shift;
    my $dist = shift;
    foreach my $_config (keys %formatMediaMap)
    {
        next if( $config !~ /^$_config$/i );

        foreach my $_dist (keys %{$formatMediaMap{$_config}})
        {
            next if( $dist !~ /^$_dist$/i );
            return ( $formatMediaMap{$_config}{$_dist}->{format}, $formatMediaMap{$_config}{$_dist}->{media} );
            last;
        }
    }
}

sub formatType  {
    my $self = shift;
    my $config = $self->_getByFieldName('productType');
    my $dist = $self->_getByFieldName('formatType');
    my( $formatType, $mediaType ) = $self->_getFormatMedia( $config, $dist );

    return $formatType if( $formatType );

    if( !$formatType )
    {
        return $self->handleError("Unknown config($config) distChannel($dist)", RPS::DB::Item::SaleImportError::kErrorFormatType );
    }
}

sub mediaType  {
    my $self = shift;
    my $config = $self->_getByFieldName('productType');
    my $dist = $self->_getByFieldName('formatType');
    my( $formatType, $mediaType ) = $self->_getFormatMedia( $config, $dist );

    return $mediaType if( $mediaType );

    return $self->handleError("Unknown config($config) distChannel($dist)", RPS::DB::Item::SaleImportError::kErrorMediaType );
}

sub albumName {
    my $self = shift;
    my $albumName = $self->_getByFieldName('albumName');
    return $albumName if( $self->productType eq RPS::File::Sale::TYPE_ALBUM );

    if( !defined $self->productType )
    {
        my $config = $self->_getByFieldName( 'productType' );
        return $albumName if( $config =~ /longplay|longform/i ); # if it has longplay or longform, it's probably an album
    }
}

sub upc {
    my $self = shift;
    my $upc = $self->_getByFieldName('upc');
    return $upc if( $self->productType eq RPS::File::Sale::TYPE_ALBUM );

    if( !defined $self->productType )
    {
        my $config = $self->_getByFieldName( 'productType' );
        return $upc if( $config =~ /longplay|longform/i ); # if it has longplay or longform, it's probably an album
    }
}

sub trackName {
    my $self = shift;
    my $trackName = $self->_getByFieldName('trackName');
    return $trackName if( $self->productType eq RPS::File::Sale::TYPE_TRACK );

    if( !defined $self->productType )
    {
        my $config = $self->_getByFieldName( 'productType' );
        return $trackName if( $config !~ /longplay|longform/i ); # if it doesn't have longplay or longform, it's probably a track
    }
}

sub isrc {
    my $self = shift;
    my $isrc = $self->_getByFieldName('isrc');
    return $isrc if( $self->productType eq RPS::File::Sale::TYPE_TRACK );

    if( !defined $self->productType )
    {
        my $config = $self->_getByFieldName( 'productType' );
        return $isrc if( $config !~ /longplay|longform/i ); # if it doesn't have longplay or longform, it's probably a track
    }
}

# _processSheet is used to process a tab from the spreadsheet.
# Here, we're extracting the sale date and label information
# from the cells called out in the template.
#
sub _processSheet {
    my $self     = shift;
    my $sheet    = shift;
    my $sheetnum = shift;

    my $startDate = $sheet->[2][5];  # F3 (row 2, col 5)

    my($dateBegin, $dateEnd) = $self->_getDates( date_begin => $startDate );
    $self->{_startDate} = $dateBegin;
    $self->{_endDate}   = $dateEnd;


    my $labelName = $sheet->[5][0];  # A6 (row 5, col 0)
    $self->{_labelName} = $labelName;

    return $self->SUPER::_processSheet( $sheet, $sheetnum );
}

sub price {
    my $price = abs( shift->SUPER::price() );
    return $price;
}

sub units {
    my $self = shift;
    my $units = $self->SUPER::units() || return;
    my $price = $self->SUPER::price();

    # The 'sign' of the units is driven by the price.
    # If the price is negative, we'll store negative units,
    # regardless of whether the units were positive or negative
    # in the sale file.  Accordingly, the price is always
    # positive.  This ensure that the returns are recorded
    # correctly.
    #
    if( defined($price) )
    {
        return $price < 0 ? abs($units) * -1 : abs($units);
    }
    else
    {
        return $units;
    }
}

sub unitPrice { abs( shift->SUPER::unitPrice ) }

#####    MapFace    #####
#

sub _mapFaceCompatibleVersions {
    return(11,16,24);
}

sub _mapFaceServiceID {
    return('serviceID');
}

sub _mapFaceCountryCode {
    return('countryCode');
}

sub _mapFaceProductType {
    return('productType');
}

sub _mapFaceFormatType {
    return('productType', 'formatType');
}

sub _mapFaceMediaType {
    return('productType', 'formatType');
}

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