package RPS::Import::INGrooves::v11;

use strict;

use lib '/app/tools/common/lib';
use Common::Date;
use Common::Country;

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

use Data::Dumper;

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

sub _fieldMap {
    {
        serviceID        => 'B',
        labelName        => 'L',
        countryCode      => 'J',
        dateBegin        => 'A',
        productType      => 'O',    # PRODUCT TYPE
        formatType       => 'N',    # ASSET TYPE
        mediaType        => 'M',    # SALES TYPE
        artistName       => 'C',
        serviceProductID => 'I',    # CATALOG
        upc              => 'E',
        albumName        => 'D',
        trackName        => 'F',
        isrc             => 'G',
        units            => 'P',
        price            => 'R',
    };
}

sub currencyCode { 'USD' }

sub countryCode {
    my $self = shift;
    my $name = $self->SUPER::countryCode();

    $self->fail("Country not set") unless ($name);

    $name =~ s/,.*//;

    $name = $self->_getAlternateCountryName($name) || $name;

    my $country = new Common::Country( search => $name );

    $self->fail("Could not determine country from '$name'") unless ($country);
    return $country->alpha2();
}

sub preProcessLine {
    my $self = shift;

    $self->{preLine} = undef;

    my $units;
    my $price;
    my $unitPrice;
    my $serviceID;
    my $productType;
    my $formatType;
    my $mediaType;

    my $INGretailer    = $self->_serviceName();
    my $INGproductType = $self->_getByFieldName('productType');
    my $INGassetType   = $self->_getByFieldName('formatType');
    my $INGsalesType   = $self->_getByFieldName('mediaType');

    ( $serviceID, $formatType, $productType, $mediaType ) =
      $self->_getServiceFormat( $INGretailer, $INGsalesType, $INGassetType, $INGproductType );

    $units = $self->_getByFieldName('units');
    $price = $self->_getByFieldName('price');

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

    # for BeatPort, multi-unit "track" sales are really albums, so we'll coerce units to 1
    # and change the product type to reflect that. awesome.
    if (   $serviceID == Client::Service::DSP_BEATPORT
        && $productType eq RPS::File::Sale::TYPE_TRACK
        && abs($units) > 1
        && !$self->_getByFieldName('isrc')
        && !$self->_getByFieldName('trackName') ) {
        $units /= $units;
        $productType = RPS::File::Sale::TYPE_ALBUM;
    }

    if ($units) {
        $unitPrice = $price / $units;
    }

    # coerce downloads and ringtones to streams if they seem too "cheap" and only if we're talking US $
    if ($formatType) {
        if ( $self->currencyCode eq 'USD' ) {
            if ($unitPrice) {
                if ( $formatType eq RPS::File::Sale::FORMAT_DOWNLOAD ) {
                    if ( $productType eq RPS::File::Sale::TYPE_TRACK && $unitPrice < .20 ) {
                        $formatType = RPS::File::Sale::FORMAT_STREAM;
                    } elsif ( $productType eq RPS::File::Sale::TYPE_ALBUM && $unitPrice < 2 ) {
                        $formatType = RPS::File::Sale::FORMAT_STREAM;
                    }
                } elsif ( $formatType eq RPS::File::Sale::FORMAT_RINGTONE ) {
                    if ( $unitPrice < .50 ) {
                        $formatType = RPS::File::Sale::FORMAT_STREAM;
                    }
                }
            }
        }
    }

    $self->{preLine}{serviceID}   = $serviceID;
    $self->{preLine}{productType} = $productType;
    $self->{preLine}{formatType}  = $formatType;
    $self->{preLine}{mediaType}   = $mediaType;
    $self->{preLine}{units}       = $units;
    $self->{preLine}{price}       = $price;
}

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

    return $self->{preLine}{productType} if ( $self->{preLine}{productType} );

    $self->fail("Unknown product type '$_productType'");
}

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

    return $self->{preLine}{formatType} if ( $self->{preLine}{formatType} );

    $self->fail("Unknown asset type '$assetType'");
}

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

    return $self->{preLine}{mediaType} if ( $self->{preLine}{mediaType} );

    $self->fail("Unknown media type '$salesType'");
}

sub _serviceName {
    my $self = shift;
    my $service = $self->_getByFieldName('serviceID') || return;
    $service =~ s/ (\w{3})$//;

    return $service;
}

sub serviceID {
    my $self    = shift;
    my $service = $self->_serviceName();

    return $self->{preLine}{serviceID} if ( $self->{preLine}{serviceID} );

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

sub price {
    return shift->{preLine}{price};
}

sub units {
    return shift->{preLine}{units};
}

sub _isValidSaleRecord {
    my $self = shift;

    # Ignore blank lines.
    my $blankLine = 1;
    foreach my $cell ( @{ $self->line } ) {
        if ( $cell ne '' ) {
            $blankLine = 0;
        }
    }
    if ( $blankLine == 1 ) { return 0; }

    # Ignore the total line
    my $formatType = $self->_getByFieldName('formatType');
    if ( $formatType =~ /total/i ) { return 0; }

    # For albums, we need either a UPC or Album Name
    if ( $self->productType eq RPS::File::Sale::TYPE_ALBUM ) {
        if ( $self->albumName || $self->upc ) {
            return 1;
        } else {
            $self->fail("Missing title and upc for album product");
        }
    }

    # For tracks, we need either an ISRC or Track Name
    if ( $self->productType eq RPS::File::Sale::TYPE_TRACK ) {
        if ( $self->trackName || $self->isrc ) {
            return 1;
        } else {
            $self->fail("Missing title and isrc for track product");
        }
    }

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

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