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

package RPS::Import::BelieveDigital::v4;

use strict;

use lib '/app/tools/data_classes/lib';
use Client::Service;

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

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

sub _fieldMap {
    {
        labelName     => 'F',
        serviceID     => 'C',
        countryCode   => 'D',
        dateBegin     => 'B',
        dateEnd       => 'B',
        formatType    => 'O',
        artistName    => 'G',
        serviceProductID => 'M',
        upc           => 'J',
        albumName     => 'H',
        isrc          => 'L',
        trackName     => 'I',
        units         => 'P',
        price         => 'V',
	  }
}

sub _unverifiedFieldMap {{
}};


sub _headerIdentifier { ( labelName => 'Label' ) }

sub mediaType   { RPS::DB::Item::MediaType::kMediaTypeAudio }

sub currencyCode { 'EUR' }

sub countryCode {
	my $self = shift;
	my $country = lc($self->_getByFieldName( 'countryCode' ));
	my $serviceName = lc($self->_getByFieldName( 'serviceID' ));

    my %countryMap = (
        'chili'         => 'chile',
        'congo  the democratic republic of the' => 'congo, the democratic republic of the',
        'cote d ivoire' => 'ci',
        'bosnia and herzefovi' => 'bosnia and herzegovina',
        'bosnia and herzegovi' => 'bosnia and herzegovina',
        'iran, islamic republ' => 'iran, islamic republic of',
        'iran  islamic republ'  => 'ir',
        'korea  republic of'   => 'kr',
        'lao people s democratic republic' => 'lao people\'s democratic republic',
        'macedonia  the former yugoslav republic of'  => 'mk',
        'moldova  republic of' => 'md',
        'palestine' => 'palestinian territory, occupied',
        'palestinian territory  occupied' => 'palestinian territory, occupied',
        "r+\x{00ac}union"      => 'ru',
        'taiwan  province of china'   => 'tw',
        'taiwan,province of china'   => 'tw',
        'tanzania  united republic of'  => 'tz',
        'timorleste'           => 'timor-leste',
        'virgin islands  u.s.' => 'virgin islands, u.s.',
    );

    my $_country = $countryMap{ lc $country } || $country;

    $_country = 'ci' if( $_country =~ /c(.*)te d ivoire$/i );

    if( $_country eq 'world' &&
        ( $self->serviceID eq Client::Service::DSP_RDIO ||
          $self->serviceID eq Client::Service::DSP_YOUTUBE ) )
    {
        $_country = 'us';
    }

    if( $_country )
    {
        my $c = Common::Country->Get( $_country );
        return $c->alpha2 if( $c );
    }

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

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

	# If there's a track name, it's a track.
	if( $track ) {
		return RPS::File::Sale::TYPE_TRACK;

	# Otherwise it's an album.
	} else {
		return RPS::File::Sale::TYPE_ALBUM;
	}
}

sub formatType {
	my $self = shift;
	my $value = $self->_getByFieldName( 'formatType' );
	
	if( $value =~ /full/i || $value =~ /download/i ) {
		return RPS::File::Sale::FORMAT_DOWNLOAD;
	} elsif ( $value =~ /stream/i ) {
		return RPS::File::Sale::FORMAT_STREAM;
	}
	
    return $self->handleError("Unknown format: $value", RPS::DB::Item::SaleImportError::kErrorFormatType );
}

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

    if ( $service )
    {
        $serviceID = $self->getServiceID( $service ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };
    }
    
    # These are adjustments, so we'll just map them back to the client.
    #
    if ($service eq 'DRM Correction Q3 2011')
    {
      $serviceID = Client::Service::DSP_BELIEVE_DIGITAL; 
    }
    
    # Can't find a match for these, so just map them to the parent service. FB6811
    if ( !$serviceID && ($service =~ /^cylo dto$/i || $service =~ /^cylo subscription$/i) )
    {
      $serviceID = Client::Service::DSP_BELIEVE_DIGITAL; 
    }    

    if (!$serviceID)
    {
        return $self->handleError("Unknown serviceID $service", RPS::DB::Item::SaleImportError::kErrorService );
    }

    return $serviceID;
}

sub price {
    my $self = shift;
    my $price = $self->_getByFieldName( 'price' );
    
    if ($price < 0)
    {
        $price *= -1;    
    }
    
    return $price;    
}

sub free {
    my $self = shift;

    my $price = $self->_getByFieldName( 'price' );

    if( exists $self->_unverifiedFieldMap->{'offerType'} )
    {
        my $offerType = $self->_getByFieldName('offerType');
        return ( $offerType =~ /(free|promo)/i && $price == 0 ) ? 1 : 0;
    }

    return ( $price == 0 ) ? 1 : 0;
}

sub units {
    my $self = shift;
    my $price = $self->_getByFieldName( 'price' );
    my $units = $self->_getByFieldName( 'units' );
    
    if ($price < 0 && $units > 0)
    {
        $units *= -1;    

    }      
    
    if ($price != 0 && $units == 0)
    {     
      $self->fail( "Revenue $price with no units" )
    }
    
    return $units;    
}

# For some reason we have negative price and a positive units.  We need to accept
# this value, so we disable the validation.
sub _validatePrice
{
    my ($self, $saleRec) = @_;
    my $price = $saleRec->price || return;

    # 0 | 0.0 | .00 |0.
    if($price !~ /^-?(?:(?:\d+)?\.\d+|\d+(?:\.)?(?:\d+)?)$/)
    {
        die Import::ValidationError->new($saleRec, "Price $price is in an incorrect format");
    }     
}

sub unitPrice {
    my $self = shift;
	  my $netPrice = $self->_formatPrice( $self->price() );
	  #print STDERR "price is $netPrice, units is " . $self->units . "/n";
	  my $unitPrice = $netPrice / $self->units() if( $self->units() );

    if ($unitPrice < 0)
    {
        $unitPrice *= -1;
    }

    return $unitPrice;
}

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

sub _mapFaceCompatibleVersions {
    return( 4,5,6,7,8,9,11,12 );
}

sub _mapFaceServiceID {
    return('serviceID');
}

sub _mapFaceCountryCode {
    return('countryCode');
}

sub _mapFaceProductType {
    return('productType');
}

sub _mapFaceFormatType {
    return('formatType');
}

sub _mapFaceMediaType {
    return('mediaType');
}

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