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

package RPS::Import::PIAS::v4;

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',
        artistName       => 'B',
        albumName        => 'C',
        priceLevel       => 'I',
        retailPrice      => 'M',
        totalRevenue     => 'Q',                            
    }
}

sub _unverifiedFieldMap {
    {
        netUnits => 'K',
    }
}

sub physical { 1; }

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 channel { RPS::File::Sale::CHANNEL_RETAIL }

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

sub priceLevel { 
    my $self = shift;
    my $priceCategory = $self->_getByFieldName('priceLevel');
    
    if( $priceCategory =~ /^CREDIT NOTE$/i || $priceCategory =~ /^INVOICE$/i )
    {
        return RPS::File::Sale::PLEVEL_UNKNOWN;
    }
    elsif( $priceCategory =~ /^FULL PRICE$/i )
    {
        return RPS::File::Sale::PLEVEL_FULL;
    }
    elsif( $priceCategory =~ /^MID PRICE$/i )
    {
        return RPS::File::Sale::PLEVEL_MID;
    }
    $self->fail("Unable to get price level from $priceCategory");
}

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 $countryObj  = Common::Country->Get( $cname );
    my $countryCode = $countryObj->alpha2() if( $countryObj );
    return $countryCode;
}

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

    if( $catalogNo =~ /lp$/i )
    {
        return RPS::File::Sale::TYPE_LP;
    }
    elsif( $catalogNo =~ /cd$/i ||
           $catalogNo !~ /[a-z]{2}$/i )  # if no config then default to CD
    {
        return RPS::File::Sale::TYPE_CD;
    }
    $self->fail("Unknown configuration '$catalogNo'");
}

sub sales {
    my $self = shift;
    my $netUnits = $self->_getByFieldName('netUnits');

    return ( $netUnits > 0 ) ? $netUnits : 0;
}

sub salesRevenue {
    my $self = shift;
    my $revenue = $self->_getByFieldName('totalRevenue');

    return ( $revenue > 0 ) ? $revenue : 0;
}

sub returns {
    my $self = shift;
    my $netUnits = $self->_getByFieldName('netUnits');

    return ( $netUnits < 0 ) ? abs($netUnits) : 0;
}

sub returnsRevenue {
    my $self = shift;
    my $revenue = $self->_getByFieldName('totalRevenue');
    
    return ( $revenue < 0 ) ? abs($revenue) : 0;
}

sub _isValidSaleRecord {
    my $self = shift;

    # The line is valid if it has sales or returns, and has an album title
    #
    return ( ($self->sales != 0 || $self->returns != 0) && $self->albumName );
}

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