#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (c) 2013-2014 RoyaltyShare, Inc. All Rights Reserved
#---------------------------------------------------------------
package RPS::Import::Sony::v22;

use strict;

use Date::Calc qw(Days_in_Month);

use lib '/app/tools/common/lib';
use Common::Assert;
use Data::Dumper;

use lib '/app/tools/rps/lib';

use base 'RPS::Import::MapFaceBase';
use base 'RPS::Import::Importer';

sub _fieldMap {
    {
        dateBegin   => 'K',
        countryCode => 'I',
        albumName   => 'D',
        isrc        => 'E',
        units       => 'AA',
        price       => 'AC',
        productType => 'J',
        formatType  => 'L',
    };
}

sub _unverifiedFieldMap {
    {
        productArtist => 'C',
        trackArtist   => 'G',
        trackName     => 'F',
    };
}

sub _headerIdentifier { ( 'isrc' => 'Track number' ) }

sub currencyCode { 'CAD' }

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

    if ($name) {
        my $o = Common::Country->Get($name);
        return $o->alpha2 if ($o);
    }

    return $name;    # Return original name and let MapFace deal with it

}

sub saleDates {
    my $self      = shift;
    my $startDate = $self->_getByFieldName('dateBegin');
    my $dateBegin;
    my $dateEnd;

    if ( $startDate =~ /(\d{4}) H(\d)/ ) {
        my $year = $1;
        my $half = $2;
        if ( $half eq '1' ) {
            $dateBegin = sprintf( "%04d-%02d-%02d", $year, 1, 1 );
            $dateEnd   = sprintf( "%04d-%02d-%02d", $year, 6, 30 );
        } elsif ( $half eq '2' ) {
            $dateBegin = sprintf( "%04d-%02d-%02d", $year, 7,  1 );
            $dateEnd   = sprintf( "%04d-%02d-%02d", $year, 12, 31 );
        }
    }
    return ( $dateBegin, $dateEnd );
}

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

    if ( $self->productType() eq RPS::File::Sale::TYPE_TRACK
        || ( !defined $self->productType() && $config =~ /track/i ) ) {
        return $self->_getByFieldName('trackArtist');
    } elsif ( $self->productType() eq RPS::File::Sale::TYPE_ALBUM
        || ( !defined $self->productType() && $config =~ /lp/i ) ) {
        return $self->_getByFieldName('productArtist');
    }
}

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

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

    if ( $config =~ /^audio-lp$/i ) {
        return RPS::File::Sale::TYPE_ALBUM;
    } elsif ( $config =~ /^(aud|vid)-track$/i || $config =~ /^ring(back|tone)$/i ) {
        return RPS::File::Sale::TYPE_TRACK;
    } else {
        return $self->handleError( "Unknown config: $config", RPS::DB::Item::SaleImportError::kErrorProductType );
    }
}

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

    if ( $distChannel =~ /^streamin$/i || $distChannel =~ /^BRKG-(SUB|ONL)$/i || $distChannel =~ /^\s*$/i ) {
        return RPS::File::Sale::FORMAT_STREAM;
    } elsif ( $distChannel =~ /^mobile$/i ) {
        return RPS::File::Sale::FORMAT_RINGTONE;
    } elsif ( $distChannel =~ /^download$/i ) {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    } else {
        return $self->handleError( "Unknown distChannel: $distChannel", RPS::DB::Item::SaleImportError::kErrorFormatType );
    }
}

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

    if ( $config =~ /^aud-track$/i || $config =~ /^audio-lp$/i || $config =~ /^ring(back|tone)$/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    } elsif ( $config =~ /^vid-track$/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeVideo;
    } else {
        return $self->handleError( "Unknown config: $config", RPS::DB::Item::SaleImportError::kErrorMediaType );
    }
}

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

    $units =~ s/,//;

    return $price < 0 ? abs($units) * -1 : abs($units);
}

sub price {
    my $price = abs( shift->SUPER::price() );
    return $price;
}

sub unitPrice {
    my $price = abs( shift->SUPER::unitPrice() );
    return $price;
}

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

    return $name if ( $self->productType() eq RPS::File::Sale::TYPE_ALBUM );

    if ( !defined $self->productType() ) {
        my $config = $self->_getByFieldName('productType');
        return $name if ( $config =~ /lp/i );    # if the config has 'lp', it's probably an album
    }
}

sub trackName {
    my $self = shift;
    my $name;

    $name = $self->_getByFieldName('trackName');
    $name = $self->_getByFieldName('albumName') if ( '' eq $name );

    return $name if ( $self->productType() eq RPS::File::Sale::TYPE_TRACK );

    if ( !defined $self->productType() ) {
        my $config = $self->_getByFieldName('productType');
        return $name if ( $config =~ /track/i );    # if the config has 'track', it's probably a track
    }
}

sub _isValidSaleRecord {
    my $self = shift;

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

    # In order to catch invalid product types with MapFace,
    # we'll relax the _isValidSaleRecord criteria a little --
    # if there's a config defined BUT it's not a valid RPS
    # product type, then allow the line as long as it has
    # units (the album/track name info will be empty since it
    # is populated only once we have a valid RPS product type).
    #
    return 1
      if ( defined( $self->units )
        && $config
        && $self->productType ne RPS::File::Sale::TYPE_ALBUM
        && $self->productType ne RPS::File::Sale::TYPE_TRACK );

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

#####    MapFace    #####
#

sub _mapFaceServiceID {
    return ('serviceID');
}

sub _mapFaceCountryCode {
    return ('countryCode');
}

sub _mapFaceProductType {
    return ('productType');
}

sub _mapFaceFormatType {
    return ('formatType');
}

sub _mapFaceMediaType {
    return ('productType');
}

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