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

package RPS::Import::PIASDigital::v5;

use strict;

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

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

sub _fieldMap {
    {
        # header
        dateBegin    => 'C',
        dateEnd      => 'C',
        currencyCode => 'C',

        # detail
        countryCode     => 'G',
        clientProductID => 'D',
        upc             => 'E',
        isrc            => 'F',
        formatType      => 'I',
        artistName      => 'B',
        albumName       => 'C',
        trackName       => 'C',
        units           => 'K',
        price           => 'Q',
    };
}

sub _headerIdentifier { ( albumName => 'Product Title' ) }

sub _processSheet {
    my $self     = shift;
    my $sheet    = shift;
    my $sheetnum = shift;

    delete $self->{_shiftedColumns} if ( exists $self->{_shiftedColumns} );

    # Check for shifted columns
    #
    foreach my $line (@$sheet) {
        $self->{line} = $line;
        my $albumName = $self->_getByFieldName('albumName');

        # Check for header line and adjust offset if album name is in the wrong spot
        #
        last if ( $albumName =~ /^Product Title$/i );    # nothing to do, column is in right spot
        if ( $albumName =~ /^catalogue no\.$/i ) {

            # shifted column, set flag so we get the correct field offsets
            $self->{_shiftedColumns} = 1;
            last;
        }
    }

    # Grab data from area above the header
    #
    foreach my $line (@$sheet) {
        $self->{line} = $line;

        # We'll grab the date begin and currenty code from the header area
        #
        my $label = $self->_getByFieldName('artistName');    # get the row label

        if ( !defined $self->{_startDate} ) {
            if ( $label =~ /^Reporting Period\:$/i ) {
                my $dt = $self->_getByFieldName('dateBegin');

                # Ex. 01/07/2014 To 31/12/2014
                #
                if ( $dt =~ /^(\d{1,2})\/(\d{1,2})\/(\d{4}) To (\d{1,2})\/(\d{1,2})\/(\d{4})$/i ) {
                    my ( $sDay, $sMonth, $sYear, $eDay, $eMonth, $eYear ) = ( $1, $2, $3, $4, $5, $6 );
                    my $sdate = sprintf( "%04d-%02d-%02d", $sYear, $sMonth, $sDay );
                    my $edate = sprintf( "%04d-%02d-%02d", $eYear, $eMonth, $eDay );
                    $self->{_startDate} = $sdate;
                    $self->{_endDate}   = $edate;

                }
            }
        }

        if ( !defined $self->{_currencyCode} ) {
            if ( $label =~ /^Currency\:$/i ) {
                $self->{_currencyCode} = $self->_getByFieldName('currencyCode');
            }
        }

        last if ( $self->{_startDate} && $self->{_currencyCode} );    # all done

    }

    # Now process the rest of the sheet
    #
    $self->SUPER::_processSheet( $sheet, $sheetnum );
}

# Note: adjusting offsets only works for column notation.  It does _not_
# work if the field is specified using cell notation (e.g., "C10").
#
sub _getOffset {
    my $self  = shift;
    my $field = shift;

    my $offset = $self->SUPER::_getOffset($field) || return;
    if ( $self->{_shiftedColumns} ) {
        return $offset - 1;
    }
    return $offset;
}

sub artistName {
    my $self = shift;
    my $name = $self->_getByFieldName('artistName');
    $name =~ s/^-   //;    # Remove any cruft if necessary
    return $name;
}

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

sub saleDates {
    my $self = shift;

    return ( $self->{_startDate}, $self->{_endDate} ) if ( $self->{_startDate} );    # from header of current sheet; see _processSheet
}

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

    my %countryMap = ( 'kazakstan' => 'KZ' );
    $cname = $countryMap{ lc $cname } if ( exists $countryMap{ lc $cname } );

    my $countryObj = Common::Country->Get($cname);
    my $countryCode;
    if ($countryObj) {
        $countryCode = $countryObj->alpha2();
    } else {
        $self->fail("Unknown country '$cname'");
    }
    return $countryCode;
}

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

    return ( defined $isrc && '' eq $isrc ) ? RPS::File::Sale::TYPE_ALBUM : RPS::File::Sale::TYPE_TRACK;
}

sub formatType {
    my $self = shift;
    my $type = $self->_getByFieldName('formatType');
    if (   $type =~ /^Breakage$/i
        || $type =~ /^Cloud Streaming$/i
        || $type =~ /^Official Ad-funded Streaming Product$/i
        || $type =~ /^Streaming$/i
        || $type =~ /^Subscr' Streaming product$/i
        || $type =~ /^Subsc' Stream Prod \(A\)$/i ) {
        return RPS::File::Sale::FORMAT_STREAM;
    } elsif ( $type =~ /^A la carte download Product$/i ) {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    } elsif ( $type =~ /^Subscr' Stream prod\(teth\)$/i
        || $type =~ /^Subscription DL Product$/i ) {
        return RPS::File::Sale::FORMAT_TETHERED;
    }
    $self->fail("Unknown format '$type'");
}

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

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

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

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

sub isrc {
    Common::Util::normalize_isrc( shift->SUPER::isrc );
}

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.
###
