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

use strict;
use utf8;

use Date::Calc qw(Days_in_Month);

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

sub _fieldMap {
    {
        countryCode     => 'E',
        productType     => 'A',
        clientProductID => 'D',
        sales           => 'F',
        salesRevenue    => 'G',
        totalRevenue    => 'G',
    };
}

sub _unverifiedFieldMap {
    {
        productTitle => 'B',    # we'll get the album name and artist name from here
    };
}

sub _headerIdentifier { ( countryCode => 'Country of Sale' ) }

sub currencyCode { 'USD'; }

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

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

sub physical { 1; }

sub _parseProductTitle {
    my $self = shift;
    my $desc = $self->_getByFieldName('productTitle');

    my ($artist, $album, $config);
    # We're looking for data in a field where they're using a double-quote mark as a delimiter...
    #
    if ( $desc =~ /^([\w\-\s\/&!’';:.]+)["|“]{1,2}([\w\-\s\/&!’';:.]+)["|”]{1,2}(.+)$/i ) {    #  artistName"albumTitle"config
        ( $artist, $album, $config ) = ( $1, $2, $3 );
        $artist = Common::Util::trimspaces($artist);
        $album  = Common::Util::trimspaces($album);
    } else {
        # Ok, the field isn't what we expect, so we'll leave the artist blank and put everything
        # in the album field.
        #
        $artist = "";
        $album  = Common::Util::trimspaces($desc);
    }
    return ( $artist, $album, $config );
}

sub albumName {
    my $self = shift;
    my ( $artist, $album, $config ) = $self->_parseProductTitle();
    return $album;
}

sub artistName {
    my $self = shift;
    my ( $artist, $album, $config ) = $self->_parseProductTitle();
    return $artist;
}

sub retailPrice {
    my $self     = shift;
    my $revenue  = $self->_getByFieldName('salesRevenue');
    my $quantity = $self->_getByFieldName('sales');
    return $revenue / $quantity;
}

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

    # Determine the country code
    #
    my %countryMap = ();
    $name = ( exists $countryMap{ lc $name } ) ? $countryMap{ lc $name } : $name;
    if ( !$name || '' eq $name ) {
        $self->fail( "Missing country code on line " . $self->linenum );
    }
    my $o = Common::Country->Get($name);
    return ( defined $o ) ? $o->alpha2() : $name;
}

sub saleDates {
    my $self = shift;

    my $fileName = $self->{filename};

    if ( !$self->{_dateBegin} ) {

        # Get date information from the filename
        #
        if ( $fileName =~ /[_|\s](\d{2})-(\d{4}).*\.\w{3,4}$/ )    # filename contains MM-YYYY
        {
            $self->{_dateBegin} = sprintf( "%04d-%02d-%02d", $2, $1, 1 );
            $self->{_dateEnd} = sprintf( "%04d-%02d-%02d", $2, $1, Days_in_Month( $2, $1 ) );
        } else {
            $self->fail("Couldn't get dates from filename '$fileName'");
        }
    }
    return ( $self->{_dateBegin}, $self->{_dateEnd} );
}

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

    if ( $config =~ /^cd$/i ) {
        return RPS::File::Sale::TYPE_CD;
    } elsif ( $config =~ /^vinyl$/i ) {
        return RPS::File::Sale::TYPE_LP;
    } elsif ( $config =~ /^cass(?:ette)?$/i ) {
        return RPS::File::Sale::TYPE_CASS;
    }

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

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

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

sub salesRevenue {
    my $self         = shift;
    my $salesRevenue = $self->_getByFieldName('salesRevenue');
    return ( $salesRevenue > 0 ) ? $salesRevenue : 0;
}

sub returns {
    my $self         = shift;
    my $sales        = $self->_getByFieldName('sales');
    my $salesRevenue = $self->_getByFieldName('salesRevenue');
    return ( $sales < 0 && $salesRevenue < 0 ) ? abs($sales) : 0;
}

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

sub _isValidSaleRecord {
    my $self = shift;

    if ( !$self->sales && !$self->returns && $self->totalRevenue ) {
        $self->fail("ERROR while processing physical sale record. Units = 0 and Revenue IS NOT 0")
    }

    return ( $self->sales || $self->returns ) && $self->albumName;
}

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