package RPS::Import::PIASDigital::v4;

use strict;

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

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

use Data::Dumper;
use Date::Calc qw(Days_in_Month Decode_Month);

sub _headerIdentifier { ( upc => 'BARCODE' ) }

# Note: some variants of v4 sales files may have shifted columns
# due to the presence of a blank column.  E.g., what may look like
# column B in Excel actually appears as column A when viewed here
# in the importer.  There is some logic here to deal with it (see
#
#
sub _fieldMap {
    {
        # Summary tab
        dateBegin        => 'A',
        currencyCode     => 'A',

        # Royalty detail tab(s)
        serviceID        => 'F',
        countryCode      => 'E',

        artistName       => 'A',
        upc              => 'D',
        isrc             => 'C',
        albumName        => 'B',
        trackName        => 'B',
        units            => 'P',
        price            => 'Q',
    }
}

sub _unverifiedFieldMap {
    {
        priceCategory    => 'H',
        fmtType          => 'G',
    }
}

# If the sales file has a summary tab, the date and currency code information for
# all sales will come from the summary tab.  If there is no summary tab, then we'll
# get the information from the header section of each 'digital' sheet.  This method
# facilitates the gathering of date/currency data regardless of the sheet name.
#
sub _getDataFromSheet {
    my $self = shift;
    my $sheet = shift;
    my $sheetnum = shift;

    # Check for shifted columns before we try to pull the
    # date and currency code information
    #
    foreach my $line (@$sheet) {
        $self->{line} = $line;

        # peek at columns A and B.  If the columns are shifted, then we'll
        # see column A's data in column B.
        #
        my $colA = $self->_getByFieldName('dateBegin');
        my $colB = $self->_getByFieldName('albumName');

        if( defined $colA && $colA =~ /^Statement To\:$/i )
        {
            $self->{_shiftedColumns} = -1;  # see _getOffset
            last;
        }
    }

    # Get the date and currency code info from the pre-header area
    #
    foreach my $line(@$sheet)
    {
        $self->{line} = $line;

        # There are two variants of the summary page for the v4 importer:
        # a) The date and currency code information are in single, separate
        #    cells with no label;
        # b) The date (and currency code) information has a label in one cell
        #    with the corresponding data in an adjacent cell.
        #
        my $rowLabel = $self->_getByFieldName('albumName');
        my $altData = $self->_getByFieldName('countryCode');


        # Get the date from the header
        #
        if( !$self->{_startDate} )
        {
            if( $self->_getByFieldName('dateBegin') =~ /for period (\w+) (\d{4}) to (\w+) (\d{4})/i )
            {
                my $startMonth = Decode_Month($1);
                my $startYear  = $2;

                my $endMonth = Decode_Month($3);
                my $endYear  = $4;

                $self->{_startDate} = sprintf( "%04d-%02d-%02d", $startYear, $startMonth, 1 );
                $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $endYear, $endMonth, Days_in_Month($endYear, $endMonth) );
            }
            elsif( $rowLabel && $rowLabel =~ /^Period\:$/i )
            {
                if( $altData && $altData =~ /(\d{2})\/(\d{2})\/(\d{4}) to (\d{2})\/(\d{2})\/(\d{4})/i )
                {
                    my($sDay, $sMonth, $sYear) = ($1, $2, $3);
                    my($eDay, $eMonth, $eYear) = ($4, $5, $6);
                    $self->{_startDate} = sprintf( "%04d-%02d-%02d", $sYear, $sMonth, $sDay );
                    $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $eYear, $eMonth, $eDay );
                }
            }
        }

        # Look for the currency code information
        #
        if( !$self->{_currencyCode} )
        {
            my $ccode;
            if( $self->_getByFieldName('currencyCode') =~ /all amounts printed in (\w+)/i )
            {
                $ccode = $1;
            }
            elsif( $rowLabel && $rowLabel =~ /^Currency\:$/i )
            {
                $ccode = $altData;
            }

            # Make sure the currency code is legit
            #
            if( $ccode =~ /^eur|euro$/i )
            {
                $self->{_currencyCode} = 'EUR';
            }
            elsif( $ccode =~ /^gbp$/i )
            {
                $self->{_currencyCode} = 'GBP';
            }
        }

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

    }#line
}

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

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


    if( !defined $self->{_hasSummaryTab} )
    {
        if( $self->{sheetname} =~ /^digital$/i )
        {
            # If there is no summary tab, get the date and currency code info from
            # the pre-header area of the sales detail tab
            #
            $self->{_startDate} = undef;
            $self->{_currencyCode} = undef;

            $self->_getDataFromSheet( $sheet, $sheetnum );


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

    }
    else
    {
        # If there is a summary tab, we will have already gotten the date/currency
        # information when _preProcess() was called.  All we have to do now is
        # process the non-summary tab if it has header.
        #

        # But first, check for shifted columns
        #
        foreach my $line (@$sheet) {
            $self->{line} = $line;
            my $albumName = $self->_getByFieldName('albumName'); # normally column B, unless shifted

            # Check for header line and adjust offset if album name is in the wrong spot
            #
            last if ( $albumName =~ /^PRODUCT$/i ); # column in right spot

            if( $albumName =~ /^ARTIST$/i )
            {
                # shifted column, set the correct field offset
                #
                $self->{_shiftedColumns} = 1;  # see _getOffset
                last;
            }
        }

        return $self->SUPER::_processSheet( $sheet, $sheetnum );
    }
}#_processSheet

# Note: adjusting offsets only works for column notation.  It does _not_
# work if the field is specified using cell notation (e.g., "C10").
# Also, we can shift left or right depending on the value of _shiftedColumns.
#
sub _getOffset {
    my $self = shift;
    my $field = shift;

    my $offset = $self->SUPER::_getOffset($field);
    return undef if( !defined $offset );
    if( $self->{_shiftedColumns} )
    {
        return $offset + $self->{_shiftedColumns};
    }
    return $offset;
}

sub _preProcess {
    my( $self, %args ) = @_;

    Log->info( "Starting _preProcess" );
    $self->SUPER::_preProcess(%args);

    # Does this workbook have a summary tab?  If so then we'll grab the
    # date and currency information from it and apply it to all sales
    # across all sheets.  Otherwise, we'll process each sheet separately
    # for the date and currency data.
    #
    my $sheetNames = $args{sheet_names};
    my $sheetnum = 0;

    foreach my $sheet(@{ $args{sheets} })
    {
        my $sheetName = $sheetNames->[$sheetnum];

        if( $sheetName =~ /^summary$/i )
        {
            $self->{_hasSummaryTab} = 1;

            # Get the date and currency code info from the pre-header area
            #
            $self->{_startDate} = undef;
            $self->{_currencyCode} = undef;

            $self->_getDataFromSheet( $sheet, $sheetnum );
        }

        $sheetnum++;
    }

}
sub currencyCode {
    my $self = shift;
    return( $self->{_currencyCode} ) if( $self->{_currencyCode} ); # from header; see _preProcess
    $self->fail("Unable to read currency code from header");
}

sub saleDates {
    my $self = shift;
    return ($self->{_startDate}, $self->{_endDate}) if( $self->{_startDate} ); # from header; see _preProcess
}

sub serviceID {
    my $self = shift;
    my $name = $self->_getByFieldName('serviceID');
    $name =~ s/\(settlement\)//;
    $name = 'NOKIA' if ($name =~ /^NOKIA - /i);

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

    return $serviceID if( $serviceID );

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

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

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

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

sub productType {
    my $self = shift;
    my $type = $self->_getByFieldName('fmtType');
    if( $type =~ /^digital (album|ep)$/i )
    {
        return RPS::File::Sale::TYPE_ALBUM;
    }
    elsif( $type =~ /^digital (track|single)$/i    ||
           $type =~ /^full audio track download$/i ||
           $type =~ /^digital video short form$/i  ||
           $type =~ /^stream$/i )
    {
        return RPS::File::Sale::TYPE_TRACK;
    }
    $self->fail( "Unable to determine product type from '$type'" ) if ( $type );
}

sub formatType  {
    my $self = shift;
    my $priceCat = $self->_getByFieldName('priceCategory');

    if( $priceCat =~ /^ad-fund dl product$/i                   ||
        $priceCat =~ /^breakage$/i                             ||
        $priceCat =~ /^cloud streaming$/i                      ||
        $priceCat =~ /^invoice$/i                              ||
        $priceCat =~ /^official ad-funded streaming product$/i ||
        $priceCat =~ /^streaming$/i                            ||
        $priceCat =~ /^subscr' streaming product$/i            ||
        $priceCat =~ /^subsc' stream prod \(a\)$/i             ||
        $priceCat =~ /^discount subsc' streaming product$/i    ||
        $priceCat =~ /^radio streaming product$/i              ||
        $priceCat =~ /^subsc' ugc product$/i                   ||
        $priceCat =~ /^ugc ad-funded streaming product$/i )
    {
        return RPS::File::Sale::FORMAT_STREAM;
    }
    elsif( $priceCat =~ /^a la carte download product$/i ||
        $priceCat =~ /^settlement$/i )
    {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    }
    elsif( $priceCat =~ /^subscription dl product$/i   ||
           $priceCat =~ /^subscr' stream prod\(teth\)/i )
    {
        return RPS::File::Sale::FORMAT_TETHERED;
    }

    $self->fail("Unable to determine format from price category ($priceCat)");
}

sub mediaType {
    my $self = shift;
    my $type = $self->_getByFieldName('fmtType');
    if( $type =~ /^digital (album|track|single|ep)$/i )
    {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    }
    elsif( $type =~ /^digital video short form$/i )
    {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    }
    $self->fail("Unknown media type '$type'");
}

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

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

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() );
}

sub _isValidSaleRecord
{
    my $self = shift;
    my $type = $self->_getByFieldName('fmtType');
    my $priceCat = $self->_getByFieldName('priceCategory');

    # error out if license income detected
    #
    if( $type =~ /^third party compilation \(royalties only\)$/i ||
        $priceCat =~ /^compilations$/i )
    {
        $self->fail("License income detected");
    }

    return $self->SUPER::_isValidSaleRecord();
}

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