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

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

use lib '/app/tools/common/lib';
use Common::Country;
use Common::RSMath qw(round);

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

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

sub _fieldMap {
    {
        dateBegin     => 'A',
        countryCode   => 'C',
        artistName    => 'H',
        productType   => 'I',
        units         => 'K',
        price         => 'S',
    }
}

sub _unverifiedFieldMap {
    {
        itemID        => 'F', # upc or isrc
        itemTitle     => 'G', # album or track title
        salesType     => 'E',
    }
}

sub _headerIdentifier { ( dateBegin => 'Accounting Quarter' ) }

sub _processHeader {
    my $self = shift;

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

    if( $self->_isHeader() )
    {
        if( $price =~ /Due (.*)/ )
        {
            if( $1 =~ /^\xA3$/ )
            {
                $self->{_currencyCode} = 'GBP';
            }
        }
    }
    return $self->SUPER::_processHeader(@_);
}

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

sub saleDates {
    my $self = shift;
    my $dt = $self->_getByFieldName('dateBegin');

    my $startDate;
    my $endDate;

    if( $dt =~ /^(\d{4})(\d{1})$/ )
    {
        my($year, $quarter) = ($1, $2);

        ($startDate,$endDate) = $self->_getDates( date_begin => "$year Q$quarter" );
    }

    return( $startDate, $endDate );
}

sub upc {
    my $self = shift;
    my $upc = $self->_getByFieldName('itemID');
    if( $self->productType eq RPS::File::Sale::TYPE_ALBUM )
    {
        $upc =~ s/^10//; # remove leading "10"
        return $upc;
    }

    if( !defined $self->productType )
    {
        $upc =~ s/^10//; # remove leading "10"
        return $upc if( $upc =~ /^\d+$/ ); # if it's all numbers then it might be a UPC ...
    }
}

sub isrc {
    my $self = shift;
    my $isrc = $self->_getByFieldName('itemID');
    if( $self->productType eq RPS::File::Sale::TYPE_TRACK )
    {
        $isrc =~ s/^5//; # remove leading "5"
        return $isrc;
    }

    if( !defined $self->productType )
    {
        $isrc =~ s/^5//; # remove leading "5"
        return $isrc if( $isrc =~ /^[a-z]{2}/i ); # if it starts with 2 letters then it might be an ISRC ...
    }
}

sub albumName {
    my $self = shift;
    my $name = $self->_getByFieldName('itemTitle');

    if( !defined $self->productType )
    {
        my $upc = $self->upc;
        return $name if( $upc );
    }

    return ($self->productType eq RPS::File::Sale::TYPE_ALBUM) ? $name : undef;
}

sub trackName {
    my $self = shift;
    my $name = $self->_getByFieldName('itemTitle');

    if( !defined $self->productType )
    {
        my $isrc = $self->isrc;
        return $name if( $isrc );
    }

    return ($self->productType eq RPS::File::Sale::TYPE_TRACK) ? $name : undef;
}

sub _processLine {
    my $self = shift;
    my $code = $self->_getByFieldName('productType'); # config desc
    my $itemID = $self->_getByFieldName('itemID');
    undef $self->{_productType};

    # Determine the product type before we start processing the line
    #

    if( $code =~ /^CD Album$/i || $code =~ /^eAlbum Audio$/i || $code =~ /^eSingle Audio\/Multi Track$/i )
    {
        $self->{_productType} =  RPS::File::Sale::TYPE_ALBUM;
    } 
    elsif( $code =~ /^E Track Audio$/i )
    {
        $self->{_productType} =  RPS::File::Sale::TYPE_TRACK;
    } 
    elsif( '' eq $code )
    {
        # If config desc is blank, peek at item ID.  After stripping off the leading "5",
        # if the leading character is a letter, then the item ID is an ISRC so this is a
        # track product.
        #
        if( $itemID =~ /^5[a-z]{2}/i )
        {
            $self->{_productType} =  RPS::File::Sale::TYPE_TRACK;
        }
    }

    return $self->SUPER::_processLine(@_);
}

sub productType
{
    my $self = shift;
    my $type = $self->{_productType};
    if( !defined $type )
    {
        my $code = $self->_getByFieldName('productType'); # config desc
        return $self->handleError("Unknown configuration desc: $code", RPS::DB::Item::SaleImportError::kErrorProductType );
    }
    return $type;
}

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

    if( $code =~ /^Ad-funded Streaming$/i ||
        $code =~ /^Cloud Service$/i ||
        $code =~ /^Subscription Streaming$/i )
    {
        return RPS::File::Sale::FORMAT_STREAM;
    }
    elsif( $code =~ /^Master Tone$/i || $code =~ /^Ringback Tones$/i )
    {
        return RPS::File::Sale::FORMAT_RINGTONE;
    }
    elsif( $code =~ /^Normal Retail$/i ||
           $code =~ /^Permanent Download$/i ||
           $code =~ /^Timed-Out Download$/i ||
           $code =~ /^Video Clip \/ Video Tone$/i )
    {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    }
    elsif( $code =~ /^Subscription Download$/i )
    {
        return RPS::File::Sale::FORMAT_TETHERED;
    }
    return $self->handleError("Unknown sales channel: $code", RPS::DB::Item::SaleImportError::kErrorFormatType );
}

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

    if( $code =~ /^Ad-funded Streaming$/i    ||
        $code =~ /^Cloud Service$/i          ||
        $code =~ /^Subscription Streaming$/i ||
        $code =~ /^Master Tone$/i            ||
        $code =~ /^Ringback Tones$/i         ||
        $code =~ /^Normal Retail$/i          ||
        $code =~ /^Permanent Download$/i     ||
        $code =~ /^Timed-Out Download$/i     ||
        $code =~ /^Subscription Download$/i )
    {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    }
    elsif( $code =~ /^Video Clip \/ Video Tone$/i )
    {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    }
    return $self->handleError("Unknown sales channel: $code", RPS::DB::Item::SaleImportError::kErrorMediaType );
}

sub countryCode {
    my $self = shift;

    my $ccode;
    my $cname = $self->_getByFieldName('countryCode');
    if( $cname =~ /^(\w{2,3})$/ ) # 2 or 3 character 
    {
        $ccode = $cname;
    }
    else
    {
        my $o = Common::Country->Get($cname);
        if( !$o )
        {
            return $cname;  # Return original name and let MapFace deal with it
        }
        $ccode = $o->alpha2();
    }
    return $ccode;
}

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

    if ($units =~ /\d\.\d+e-\d{2}/i) {
        $units = 0;
    }
    
    $units = round($units);

    # 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) && $price != 0 )
    {
        return $price < 0 ? abs($units) * -1 : abs($units);
    }
    else
    {
        return $units;
    }
}

sub _isValidSaleRecord {
    my $self = shift;

    my $code = $self->_getByFieldName( 'configDesc' );
    my $itemID = $self->_getByFieldName('itemID');

    return 0 if( '' eq $code && '' eq $itemID );

    return ( defined($self->units) && ($self->trackName || $self->albumName) );
}

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

sub _mapFaceServiceID {
    return('serviceID');
}

sub _mapFaceCountryCode {
    return('countryCode');
}

sub _mapFaceProductType {
    return('productType');
}

sub _mapFaceFormatType {
    return('salesType');
}

sub _mapFaceMediaType {
    return('salesType');
}

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