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

use strict;

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

sub _fieldMap {
    {
        labelName        => 'A',
        countryCode      => 'K',
        dateBegin        => 'B5',
        productType      => 'E',
        formatType       => 'L',
        artistName       => 'C',
        serviceProductID => 'B',
        upc              => 'F',
        isrc             => 'G',
        units            => 'R',
        price            => 'X',
    }
}

sub _unverifiedFieldMap {
    {
        title          => 'D',
        deliveryFormat => 'M',
    }
}

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

sub currencyCode { 'GBP' }

sub saleDates {
    my $self = shift;
    my $startDate = $self->{_startDate};
    return $self->_getDates( date_begin => $startDate );
}

sub free {
    my $self = shift;
    my $format = $self->_getByFieldName('deliveryFormat');
    my $price = $self->_getByFieldName('price');
    return 1 if( $format =~ /^free$/i and 0 == $price );
}

sub units {
    my $self = shift;
    my $units = $self->_getByFieldName('units');
    my $price = $self->_getByFieldName('price');
    return ($price < 0) ? (abs($units)*-1) : $units;
}

sub unitPrice {
    my $self = shift;
    my $units = $self->_getByFieldName('units') || return;
    my $price = $self->_getByFieldName('price');
    return abs($price/$units);
}

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

    if($type =~ /^(album|ep|mini album|single)$/i)
    {
        return RPS::File::Sale::TYPE_ALBUM;
    } 
    elsif($type =~ /^track$/i)
    {
        return RPS::File::Sale::TYPE_TRACK;
    } 
    else
    {
        $self->fail("Could not parse product type from '$type'");
    }
}

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

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

sub formatType  {
    my $self = shift;
    my $type = $self->_getByFieldName('formatType');
    if( $type =~ /^(cloud|stream|subscription)$/i )
    {
        return RPS::File::Sale::FORMAT_STREAM;
    }
    elsif($type =~ /^(download|full)$/i || '' eq $type)
    {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    }
    $self->fail("Could not parse format type from '$type'");
}

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

sub _preProcess {
    my $self = shift;
    my %args = @_;

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


    # Get the date information from the summary tab before we start
    # processing the file.
    #
    my $sheetNames = $args{sheet_names};
    my $sheetnum = 0;

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

        if( $sheetName =~ /^statement summary$/i )
        {
            my $linenum=1;
            foreach my $line(@$sheet)
            {
                $self->{line} = $line;

                # We should be able to find the required info within the first
                # 100 lines of the summary tab.  If not, then the following check
                # will prevent us from wasting time dealing with a large summary tab
                #
                last if( $linenum > 100 );

                # The following loop iterates over the columns in the current line.
                # This way we'll be able to detect the date information even if
                # the columns and/or rows are 'shifted' from where we expect them
                # to be.
                #
                foreach my $cell (@$line)
                {
                    if($cell =~ /^period/i && !$self->{_startDate})
                    {
                        # The date information is assumed to be in Euro format:
                        #
                        #   Period: 1/3/2017 - 31/3/2017
                        #
                        if( $cell =~ /(\d{1,2})\/(\d{1,2})\/(\d{4}) - (\d{1,2})\/(\d{1,2})\/(\d{4})/i )
                        {
                            my($sDay, $sMonth, $sYear, $eDay, $eMonth, $eYear) = ($1, $2, $3, $4, $5, $6);
                            $self->{_startDate} = sprintf( "%04d-%02d-%02d", $sYear, $sMonth, $sDay );
                            $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $eYear, $eMonth, $eDay );
                        }
                    }
                }#cell


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

                $linenum++;

            }#line
        
            last; # ONLY process summary sheet for date/currency code

        }# statement summary

        $sheetnum++;
    }

}

sub _isValidSaleRecord
{
    my $self = shift;
    my $units = $self->_getByFieldName('units');
    my $revenue = $self->_getByFieldName('price');
    my $title = $self->_getByFieldName('title');
    
    return ( ($units || $revenue) && $title );

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

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