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

package RPS::Import::PIAS::v3;

use strict;

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

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

sub _fieldMap {
    my $self = shift;
    
    my $sheetName = $self->_normalizeSheetName( lc $self->{sheetname} );
    
    my %fieldMaps = (
        'pias uk' => {
            countryCode      => 'E',
            productType      => 'G',
            artistName       => 'A',
            albumName        => 'B',
            currencyCode     => 'A19',
            wholesalePrice   => 'K',
            sales            => 'P',
            returns          => 'P',
            totalRevenue     => 'Q',                            
        },   
        'pias international' => {
            countryCode      => 'E',
            productType      => 'B',
            artistName       => 'D',
            albumName        => 'C',
            currencyCode     => 'C4',
            wholesalePrice   => 'H',
            sales            => 'G',
            returns          => 'G',
            totalRevenue     => 'K',                            
        },             
    );
            
    if ($fieldMaps{$sheetName}) {
        return $fieldMaps{$sheetName};
    }
}

sub _headerIdentifier { ( albumName => qr/PRODUCT|Title/ ) }
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 $sheetName = $self->_normalizeSheetName( lc $self->{sheetname} );    
    
    if ($sheetName eq 'pias uk') {
        return RPS::File::Sale::PLEVEL_UNKNOWN;
    }
    elsif ($sheetName eq 'pias international') {
        return RPS::File::Sale::PLEVEL_FULL;
    }
}

sub currencyCode {
    my $self = shift;
    my $currencyCode = $self->_getByFieldName( 'currencyCode' );
    if ($currencyCode =~ /All amounts printed in (\w{3})/i) {
        return $1;
    }
    elsif ($currencyCode =~ /REPORT CURRENCY:\s*(\w{3})/i) {
        return $1;
    }    
}

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' );
    
    if (!$cname) {
        return 'UK';
    }

    # %countryMap contains mappings of non-standard country names
    # to a valid country codes.
    #
    my %countryMap = (
       'swiss' => 'CH',
    );

    $cname = $countryMap{lc $cname} || $cname;

    my $countryObj  = Common::Country->Get( $cname );
    my $countryCode = $countryObj->alpha2() if( $countryObj );
    return $countryCode;
}

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

    if( $productType =~ /lp$/i )
    {
        return RPS::File::Sale::TYPE_LP;
    }
    elsif( $productType =~ /cd digipack$/i )
    {
        return RPS::File::Sale::TYPE_CD;
    }
    elsif( $productType =~ /2cd$/i )
    {
        return RPS::File::Sale::TYPE_DBL_CD;
    }  
    elsif( $productType =~ /cd$/i )
    {
        return RPS::File::Sale::TYPE_CD;
    }        

    # CD will be the default product type
    return RPS::File::Sale::TYPE_CD;
}

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

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

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

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

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

    return ( $returns < 0 ) ? abs($returns) : 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 && $self->albumName ne '===============' );
}

sub _normalizeSheetName {
    my $self = shift;
    my $sname = shift;
    my $name;

    $name = $sname;
    if ( $sname =~ /pias uk/i )
    {
        $name = "pias uk";
    }
    elsif ( $sname =~ /pias international/i )
    {
        $name = "pias international";
    }    

    return $name;
}

# _preProcess is called before we start processing the spreadsheet.
# Here, we're looking for the date information from the 'summary' tab.
# Once found, we'll save it so that it can be applied to sales found on
# the sales detail tab.
#
sub _preProcess {
    my( $self, %args) = @_;
    $self->SUPER::_preProcess(%args);
    my $fileObj = $args{file};
    $fileObj->Physical(1);

    my $sheetNames = $args{sheet_names};

    # Get the date information from the summary tab
    #
    my $sheetCount = 0;
    SHEET: foreach my $sheet(@{ $args{sheets} })
    {
        my $sheetName = $sheetNames->[$sheetCount];

        next if( $sheetName !~ /^summary\s*$/i );

        foreach my $line(@$sheet)
        {
            #$self->{line} = $line;           
            #my $date = $self->_getByFieldName( 'dateBegin' );
            
            my $date = $line->[1];

            #                DD         MM       YYYY         DD         MM       YYYY
            if( $date =~ /(\d{1,2})\/(\d{1,2})\/(\d{4}) - (\d{1,2})\/(\d{1,2})\/(\d{4})/ )
            {
                $self->{_startDate} = sprintf( "%04d-%02d-%02d", $3, $2, $1 );
                $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $6, $5, $4 );
                last SHEET;
            }
        }
        $sheetCount++;
    }
}

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