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

package RPS::Import::Caroline::v10;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

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

use lib '/app/tools/rps/lib';
use RPS::Import::ServiceMap;

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

sub _fieldMap {
    my $self = shift;
    my $version = $self->_version;

    my %field_map = (
        10 => {
            labelName     => 'C',
            countryCode   => 'A',
            dateBegin     => 'L',
            dateEnd       => 'L',
            productType   => 'E',
            formatType    => 'D',
            artistName    => 'H',
            upc           => 'F',
            albumName     => 'G',
            isrc          => 'E',
            trackName     => 'G',
            units         => 'O',
            price         => 'S',
            mediaType     => 'J',
        },
    );
    return $field_map{$version};
}

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

    my %field_map = (
        10 => {
            upc_isrc   => 'E',
        },
    );
    return $field_map{$version};
}

sub _headerIdentifier { ( upc => 'Royalty UPC' ) }

sub currencyCode { 'USD' }

sub countryCode {
	my $self = shift;
	my $country = $self->_getByFieldName( 'countryCode' );
	my $obj = Common::Country->Get( $country );
	
	return $obj ? $obj->alpha2 : undef;
}

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

    if( $type =~ /^eAlbum Audio$/i                    ||
        $type =~ /^eAlbum Audio HD$/i                 ||
        $type =~ /^CD album$/i                        ||
        $type =~ /^eAlbum Audio \+ Booklet$/i         ||
        $type =~ /^eMix Bundle Album$/i               ||
        $type =~ /^eSingle Audio\/Single Track$/i     ||
        $type =~ /^vinyl album 12\" 33 rpm$/i         ||
        $type =~ /^eMix Bundle Album \+ LP$/i         ||
        $type =~ /^eMix Bundle Album \+ Booklet$/i    ||
        $type =~ /^Mastertone\/Realtone\/Ringback$/i  ||
        $type =~ /^eSingle Audio\/Multi Track$/i      ||
        $type =~ /^eSingle Audio\/Single Track HD$/i  ||
        $type =~ /^eMix Bundle Single$/i              ||
        $type =~ /^eSingle Audio\/Multi Track HD$/i   ||
        $type =~ /^eAlbum Audio \+ Booklet HD$/i      ||
        $type =~ /^\s*$/  )
    {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    }
    elsif( $type =~ /^eSingle Video$/i || $type =~ /^eVideo Long Program$/i)
    {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    }

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

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

    if( $format =~ /^Mobile$/i )
    {
        return RPS::File::Sale::FORMAT_RINGTONE;
    }
    elsif( $format =~ /^Digital$/i )
    {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    }
    elsif( $format =~ /^Streams$/i )
    {
        return RPS::File::Sale::FORMAT_STREAM;
    }

    $self->fail("Unable to determine format type from format($format)");
}

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

    # the upc field is populated.  The upc_isrc field is populated with either a
    # upc or an isrc, so if they match, it's an album.
    if( $upc_isrc eq $upc )
    {
        return RPS::File::Sale::TYPE_ALBUM;
    } else {
        return RPS::File::Sale::TYPE_TRACK;
    }
}

sub saleDates {
    my $self  = shift;
    my $version = $self->_version;

    my $dateBegin;
    my $dateEnd;

    if( exists $self->_fieldMap->{'dateBegin'} )
    {
        my $date = $self->_getByFieldName('dateBegin');
        my %months = (
            'JAN' => '01',
            'FEB' => '02',
            'MAR' => '03',
            'APR' => '04',
            'MAY' => '05',
            'JUN' => '06',
            'JUL' => '07',
            'AUG' => '08',
            'SEP' => '09',
            'OCT' => '10',
            'NOV' => '11',
            'DEC' => '12',
        );

        if( $date =~ /(\d{4}).*(\w{3})/ ) # YYYY  MMM <- note the two spaces in between
        {
            $dateBegin = sprintf("%04d-%02d-%02d", $1, $months{uc($2)}, 1);
            $dateEnd =   sprintf("%04d-%02d-%02d", $1, $months{uc($2)}, Days_in_Month($1, $months{uc($2)}));
        }
    }

    return ($dateBegin, $dateEnd);

}

sub _isValidSaleRecord {
    my $self = shift;
    
    if (!$self->units && !$self->price) {
        return 0;   
    }
    
    my $country = $self->_getByFieldName( 'countryCode' );
    my $format  = $self->_getByFieldName( 'formatType' );
    if ($country =~ /^Total$/i || ('' eq $country && '' eq $format) ) {
        return 0;   
    }    
    
    # For albums, we need either a UPC or Album Name
    if ( $self->productType eq RPS::File::Sale::TYPE_ALBUM ) {
        if ( $self->albumName || $self->upc ) {
            return 1;
        } else {
            $self->fail( "Missing title and upc for album product" );
        }
    }

    # For tracks, we need either an ISRC or Track Name
    if ( $self->productType eq RPS::File::Sale::TYPE_TRACK ) {
        if ( $self->trackName || $self->isrc ) {
            return 1;
        } else {
            $self->fail( "Missing title and isrc for track product" );
        }            
    }    

    return $self->SUPER::_isValidSaleRecord();
}


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