package RPS::Import::ATrain;

use strict;

use Data::Dumper;
use lib '/app/tools/common/lib';
use Common::Util qw(normalize_upc normalize_isrc);
use Date::Calc qw(Days_in_Month);

use lib '/app/tools/data_classes/lib';

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

sub _headerIdentifier { ( isrc => 'ISRC' ) }

sub _fieldMap {
    my $self = shift;
    
    my %fieldMap =
    (
        1 => {
            serviceID        => 'A',
            countryCode      => 'J',
            dateBegin        => 'B',
            artistName       => 'F',
            upc              => 'D',
            albumName        => 'G',
            isrc             => 'C',
            trackName        => 'E',
            units            => 'H',
            price            => 'I',
        },
    );         
        
    return $fieldMap{$self->_version()};
}

sub formatType { RPS::File::Sale::FORMAT_DOWNLOAD }
sub currencyCode { 'USD' }
sub mediaType   { RPS::DB::Item::MediaType::kMediaTypeAudio }

sub saleDates {
    my $self = shift;
    my $dt = $self->_getDateBegin();

    if( $dt =~ /^(\d{1,2}\/\d{1,2}\/\d{2})\s\d{1,2}:\d{2}(?:a|p)m/ )  # strip out timestamp
    {
        $dt = $1;
    }
    return $self->_getDates( date_begin => $dt );
}

sub price {
    my $self = shift;
    my $price = $self->_getByFieldName( 'price' );
     
    $price =~ s/\$//g;

    if( $price =~ /^\((\d*\.?\d*)\)$/ ) {
        $price = -1 * abs($1);
    }     
    
    return $price;     
}

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

    if( $units == 0 ) {
        # If we have revenue, force a unit based on the sign of the revenue
        #
        $units = ( $price < 0 ) ? -1 :
                 ( $price > 0 ) ?  1 : 0;
    }

    if( $price < 0 ) {
        $units = -1 * abs($units);
    }
    return $units;
}

sub unitPrice { abs( shift->SUPER::unitPrice ) }

sub _validatePrice
{
    my ($self, $saleRec) = @_;
    my $price = $saleRec->price || return;

    # 0 | 0.0 | .00 |0.
    if($price !~ /^-?(?:(?:\d+)?\.\d+|\d+(?:\.)?(?:\d+)?)$/)
    {
        die Import::ValidationError->new($saleRec, "Price $price is in an incorrect format");
    }   
}

sub _isValidSaleRecord 
{
    my $self = shift;
    my $units  = $self->units;
    my $price  = $self->price;
    my $name  = $self->artistName;

    return undef if ( !($units && defined $price && $name)  );
    return 1;
}


sub serviceID {
    my $self = shift;
	my $service = $self->_getByFieldName( 'serviceID' );
	
    my $serviceID = $self->getServiceID(lc ($service)) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };	

    return $serviceID if( $serviceID );

    $self->fail( "Unknown service: $service" );
}


sub albumName {
    my $self = shift;
    
    # if albumName is blank and productType is Album, use trackName as
    # the albumName
    my $albumName = $self->_getByFieldName( 'albumName' );
    my $type = $self->productType();
    my $trackName = $self->_getByFieldName( 'trackName' );

	if ( (!defined $albumName || length($albumName) <= 0) && $type == 'A' ) {
		return $trackName;
	}
    return $albumName;
}

sub countryCode {
    my $self = shift;
    
    # if countryCode is blank, default to US
    my $name = $self->_getByFieldName( 'countryCode' );
	if ( !defined $name || $name eq '' || lc $name eq 'www' ) {
		return 'US';
	}

    $name = 'LA' if( $name =~ /^laos$/i ); # Lao People's Democratic Republic
    $name = 'CI' if( $name =~ /c.+ d'Ivoire/i ); # Cote d'Ivoire
    $name = 'RE' if( $name =~ /r.+union/i ); # Reunion

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

sub productType {
    my $self = shift;
    my $isrc = $self->isrc();

    # got this regex from Caroline/v11.pm
    if( $isrc =~ /^[A-Z][A-Z].*\d{7}$/ ) {
        return RPS::File::Sale::TYPE_TRACK;
    } 
    else {
        return RPS::File::Sale::TYPE_ALBUM;
    }
}

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

    return $isrc;
}


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