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

package RPS::Import::Cosmos::v1;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

sub _fieldMap {
    {
        # detail section of each sheet
        #
        labelName        => 'C',
        countryCode      => 'A',
        artistName       => 'D',
        clientProductID  => 'B',
        albumName        => 'E',
        upc              => 'G',
        configuration    => 'F',
        sales            => 'O',
        returns          => 'Q',
    }
}

sub _unverifiedFieldMap {
    {
        promoQuantity    => 'S',
        netValue         => 'M',
        distFee          => 'AB',
        rate             => 'I',
    }
};

sub _headerIdentifier { ( albumName => 'comsale_title' ) }

sub currencyCode { 'SEK'; }

sub channel { RPS::File::Sale::CHANNEL_RETAIL; }

sub priceLevel { RPS::File::Sale::PLEVEL_UNKNOWN; }

sub countryCode {
    my $self = shift;
    my $ccode = $self->_getByFieldName( 'countryCode' );
    my $o = Common::Country->Get( $ccode );
    return (defined $o) ? $o->alpha2() : $ccode;
}

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

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

    if( $config =~ /^cd album$/i )
    {
        return RPS::File::Sale::TYPE_CD;
    }
    elsif( $config =~ /^lp album$/i )
    {
        return RPS::File::Sale::TYPE_LP;
    }
    elsif( $config =~ /^vinyl single 7 inch$/i )
    {
        return RPS::File::Sale::TYPE_LP5;
    }

    $self->fail("Unable to determine config from format($config)");
}


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

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

sub salesRevenue {
    my $self = shift;

    my $totalRevenue = $self->totalRevenue;

    # This only works because we're not processing returns.. yet.
    #
    my $salesRevenue = $totalRevenue;

    return $salesRevenue;
}

sub returns {
    my $self = shift;
    my $returns = $self->_getByFieldName( 'returns' );
    $self->fail("Returns not supported at this time") if( $returns ); # See Case 17655
}

# We'll deal with returns revenue once we see actual examples of
# files with returns.
#
#sub returnsRevenue {
#    my $self = shift;
#}

sub totalRevenue {
    my $self = shift;

    my $netValue = $self->_getByFieldName( 'netValue' ); # M
    my $distFee  = $self->_getByFieldName( 'distFee' );  # AB
    my $rate     = $self->_getByFieldName( 'rate' );     # I

    my $totalRevenue = ($netValue + $distFee) * $rate;

    return $totalRevenue;
}

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

# _processSheet is used to process a tab from the spreadsheet.  Note that we
# do not process the 'summary' tab (this is done in _preProcess).  Also, we
# invoke the inherited _processSheet so that normal line processing occurs.
#
sub _processSheet {
    my $self     = shift;
    my $sheet    = shift;
    my $sheetnum = shift;

    my %args = @_;

    if( $self->{sheetname} =~ /sales (\d{4})_(\d{2})/i ) # YYYY-MM
    {
        $self->{_startDate} = sprintf( "%04d-%02d-%02d", $1, $2, 1 );
        $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $1, $2, Days_in_Month($1, $2) );
    }

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

sub _preProcess {
    my( $self, %args) = @_;
    $self->SUPER::_preProcess(%args);
    my $fileObj = $args{file};
    $fileObj->Physical(1);
    $fileObj->Save();
}

# _processLine: override so that we can check and create promo sales
# if necessary
#
sub _processLine {
    my $self = shift;

    my %args = shift;

    if( $self->_isValidSaleRecord() )
    {
        $self->_saveLine();
        $self->_createPromoSale();
        $self->{_linesImported}++;
    }
    else
    {
        Common::Log::Print( " -- Ignore line sheet: " . $self->sheetname . " line: " . $self->linenum );
        $self->{_linesIgnored}++;
    }
}

sub _createPromoSale {
    my $self = shift;

    my $promoUnits = $self->_getByFieldName( 'promoQuantity' );

    if( $promoUnits && $promoUnits > 0 )
    {
        # Create a promo sales record if necessary
        #
        my $sale = RPS::Import::SaleRec->new();

        # Set the promo-specific fields
        #
        $sale->sales( $promoUnits );
        $sale->priceLevel( RPS::File::Sale::PLEVEL_PROMO );
        $sale->salesRevenue( 0 );
        $sale->totalRevenue( 0 );

        # Copy the rest of the sale information
        #
        $sale->serviceID      (  $self->serviceID       );
        $sale->labelName      (  $self->labelName       );
        $sale->countryCode    (  $self->countryCode     );
        $sale->artistName     (  $self->artistName      );
        $sale->clientProductID(  $self->clientProductID );
        $sale->albumName      (  $self->albumName       );
        $sale->upc            (  $self->upc             );
        $sale->configuration  (  $self->configuration   );
        $sale->productType    (  $self->productType     );


        $sale->channel        (  $self->channel         );
        $sale->currencyCode   (  $self->currencyCode    );
        $sale->dateBegin      (  $self->{_startDate}    );
        $sale->dateEnd        (  $self->{_endDate}      );
        $sale->lineNum        (  $self->linenum         );

        $self->SUPER::_insertSale( sale => $sale );
    }
}

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