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

package RPS::Import::Catapult::v1;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

sub _fieldMap {
    {
        serviceID        => 'A',
        dateBegin        => 'B',
        dateEnd          => 'B',
        artistName       => 'D',
        albumName        => 'E',
        trackName        => 'E',
        units            => 'F',
        price            => 'I',
        countryCode      => 'G',
    }
}

sub _unverifiedFieldMap {
    {
        upcISRC          => 'C',
    }
}

sub _headerIdentifier { ( dateBegin => 'Sales Period' ) }

sub currencyCode { 'USD' }

sub saleDates {
    my $self = shift;

    my $dt = $self->_getDateBegin();

    my $dateBegin;
    my $dateEnd;

    if( $dt =~ /^(\d{4})-(\d{2})-(\d{2}) to (\d{4})-(\d{2})-(\d{2})$/i ) # YYYY-MM-DD to YYYY-MM-DD
    {
        my $sYear  = $1;
        my $sMonth = $2;
        my $sDay   = $3;

        my $eYear  = $4;
        my $eMonth = $5;
        my $eDay   = $6;

        if( $sDay != 1 || $eDay != Days_in_Month($eYear, $eMonth) )
        {
            # Start date is not valid; use the end date to determine the period
            #
            $dateBegin = sprintf("%04d-%02d-%02d", $eYear, $eMonth, 1);
            $dateEnd = sprintf("%04d-%02d-%02d", $eYear, $eMonth, Days_in_Month($eYear, $eMonth) );
        }
        else
        {
            $dateBegin = sprintf("%04d-%02d-%02d", $sYear, $sMonth, $sDay);
            $dateEnd = sprintf("%04d-%02d-%02d", $eYear, $eMonth, $eDay );
        }

    }

    return ($dateBegin, $dateEnd);
}

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

    $self->SUPER::_processHeader();

    my $unitHeader = $self->_getByFieldName('units');

    $self->{_formatType} = RPS::File::Sale::FORMAT_STREAM if( $unitHeader =~ /^streams$/i );
    $self->{_formatType} = RPS::File::Sale::FORMAT_DOWNLOAD if( $unitHeader =~ /^units$/i );
}

sub serviceID {
    my $self = shift;
    my $service = $self->_getByFieldName('serviceID');
    my $serviceID = $self->getServiceID(lc ($service)) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };
    return $serviceID if( $serviceID );

    $self->fail("Unknown service '$service'");
}

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

sub productType {
    my $self = shift;
    my $type = $self->_getByFieldName('upcISRC') || return;

    if( $type =~ /^\d/i )  # starts with digit ...
    {
        return RPS::File::Sale::TYPE_ALBUM;
    } 
    elsif( $type =~ /^[a-z]/i )  # starts with letter ...
    {
        return RPS::File::Sale::TYPE_TRACK;
    } 
    else
    {
        $self->fail( "Could not parse product type from '$type'" );
    }
}

sub upc {
    my $self = shift;
    my $type = $self->_getByFieldName('upcISRC') || return;

    return $type if( $type =~ /^\d/i );  # UPC if it starts with a digit ...
}

sub isrc {
    my $self = shift;
    my $type = $self->_getByFieldName('upcISRC') || return;

    return $type if( $type =~ /^[a-z]/i );  # ISRC if it starts with a letter ...
}

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

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

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

sub formatType  {
    my $self = shift;
    return $self->{_formatType}; # See _processHeader
}

sub units {
    my $self = shift;
    my $units = $self->_getByFieldName('units') || return;
    my $price = $self->_getByFieldName('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.
###
