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

package RPS::Import::Merlin::v19;

use strict;

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 {
    {
        dateBegin     => 'G',
        dateEnd       => 'H',

        countryCode   => 'C',
        labelName     => 'R',
        artistName    => 'J',
        upc           => 'L',
        albumName     => 'N',
        isrc          => 'I',
        trackName     => 'K',
        units         => 'P',
        price         => 'S',
    }
}

sub productType { RPS::File::Sale::TYPE_TRACK }

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

sub serviceID { Client::Service::DSP_SONY_MUSIC }

sub formatType { RPS::File::Sale::FORMAT_STREAM }

sub currencyCode {
    my $self = shift;
    return $self->{_currencyCode} if( $self->{_currencyCode} );

    $self->fail("Unable to find currency code in header");
}

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

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info( "Starting _preProcess" );
    $self->SUPER::_preProcess(%args);

    my $priceColumn;
    my $currencyCode;

    my $linenum = 0;
    foreach my $line(@{ $args{lines} })
    {
        $self->{line} = $line;

        $priceColumn = $self->_getByFieldName('price');
        if( $priceColumn =~ /^Royalty \((\w{3})\)/i )
        {
            $currencyCode = $1;
            last;
        }
        $linenum++;
    }
    $self->{_currencyCode} = $currencyCode if( $currencyCode );
}

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 ensures that returns are recorded correctly.
    #
    if( defined($price) )
    {
        return $price < 0 ? abs($units) * -1 : $units;
    }
    else
    {
        return $units;
    }
}

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

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