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

package RPS::Import::ProperUK::v2;

use strict;

use Date::Calc qw(Days_in_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';

use lib '/app/tool/common/lib';
use Common::Country;

sub _fieldMap {
    {
        labelName        => 'G',
        serviceID        => 'A',
        countryCode      => 'B',
        productType      => 'S',
        formatType       => 'U',
        serviceProductID => 'K',
        upc              => 'M',
        albumName        => 'L',
        isrc             => 'O',
        trackName        => 'N',
        units            => 'V',
        price            => 'Y',
    };
}

sub _unverifiedFieldMap {
    {
        year        => 'D',
        month       => 'E',
        trackArtist => 'H',
        albumArtist => 'I',
    };
}

sub artistName {
    my $self        = shift;
    my $trackArtist = $self->_getByFieldName('trackArtist');
    my $albumArtist = $self->_getByFieldName('albumArtist');

    return $self->productType eq RPS::File::Sale::TYPE_TRACK ? $trackArtist : $albumArtist;
}

sub upc {
    my $self = shift;
    my $upc = $self->_getByFieldName('upc') || return;
    $upc =~ s/'//g;
    return $upc;
}

sub productType {
    my $self = shift;
    my $type = $self->_getByFieldName('productType') || return;    # col S
    if ( $type =~ /^t|as|dt|cl|s|nr|av$/i ) {
        return RPS::File::Sale::TYPE_TRACK;
    } elsif ( $type =~ /^a|da$/i ) {
        return RPS::File::Sale::TYPE_ALBUM;
    }
    $self->fail("Unable to determine product type from '$type'");
}

sub formatType {
    my $self         = shift;
    my $saleFormat   = $self->_getByFieldName('productType');    # col S
    my $deliveryType = $self->_getByFieldName('formatType');     # col U

    if ($saleFormat)                                             # Use saleFormat column to determine format (FB291).
    {
        if ( $saleFormat =~ /^as|s|cl|nr|av$/i ) {
            return RPS::File::Sale::FORMAT_STREAM;
        } elsif ( $saleFormat =~ /^da|dt$/i ) {
            return RPS::File::Sale::FORMAT_DOWNLOAD;
        }
        $self->fail("Unable to determine format type from '$saleFormat'");
    } elsif ( !$saleFormat ) {

        # No sale format, use the legacy product format lookup logic
        #
        if (   $deliveryType =~ /On-Demand Stream/i
            || $deliveryType =~ /Cloud Match/i
            || $deliveryType =~ /Interactive Radio Stream/i ) {
            return RPS::File::Sale::FORMAT_STREAM;
        } elsif ( $deliveryType =~ /Permanent (Un)?restricted Download/i ) {
            return RPS::File::Sale::FORMAT_DOWNLOAD;
        } elsif ( $deliveryType =~ /Controlled Download/i ) {
            return RPS::File::Sale::FORMAT_TETHERED;
        }
        $self->fail("Unable to determine format type from '$deliveryType'");
    }

}

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

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

    my $serviceID = $self->getServiceID( lc($service) ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };

    # the following is a bit too specific to include in the ServiceMap so
    # just map it here
    #
    $serviceID = Client::Service::DSP_YOUTUBE if ( !$serviceID && $service =~ /YouTube - Youtube July 2012 Remainder/i );

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

sub currencyCode { shift->{_currencyCode} }

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

    my $obj = Common::Country->Get($country);

    return $obj ? $obj->alpha2 : undef;
}

sub _headerIdentifier { ( serviceID => 'Service Name' ) }

sub saleDates {
    my $self = shift;

    my $year = $self->_getByFieldName('year');
    my $month = $self->_getByFieldName('month') || return;

    if ( '' eq $year && $month =~ /^(\d{4})M(\d{1,2})$/i )    # Seen during FB291/FB5495 testing
    {
        $year  = $1;
        $month = $2;
        my $startDate = sprintf( "%04s-%02d-%02d", $year, $month, 1 );
        my $endDate = sprintf( "%04s-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );

        return ( $startDate, $endDate );
    } elsif ( $month =~ /^(q1|q2|q3|q4)$/i ) {
        my $startDate;
        my $endDate;
        my %quarters = (
            'q1' => { start => '01-01', end => '03-31' },
            'q2' => { start => '04-01', end => '06-30' },
            'q3' => { start => '07-01', end => '09-30' },
            'q4' => { start => '10-01', end => '12-31' },
        );

        my $startDate = sprintf( "%04s-%s", $year, $quarters{ lc $month }->{start} );
        my $endDate   = sprintf( "%04s-%s", $year, $quarters{ lc $month }->{end} );

        return ( $startDate, $endDate );
    } else {
        my %months = (
            jan => 1,
            feb => 2,
            mar => 3,
            apr => 4,
            may => 5,
            jun => 6,
            jul => 7,
            aug => 8,
            sep => 9,
            oct => 10,
            nov => 11,
            dec => 12
        );

        my $startDate = sprintf( "%04s-%02s-%02s", $year, $months{$month}, 1 );

        return $self->_getDates( date_begin => $startDate );
    }
}

sub _processHeader {
    my $self = shift;

    if ( $self->_isHeader() ) {
        my $currencyHeader = $self->_getByFieldName('price');
        if ( $currencyHeader =~ /^(\w{3}) Total Sales$/ ) {
            $self->{_currencyCode} = $1;
        }
    }
}

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