package RPS::Import::EMIMusic::Downloads::v1;

use strict;

use lib '/app/tools/data_classes/lib';
use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use lib '/app/tools/raptor/lib';
use Common::Date;
use Common::Log;
use Common::RSMath;
use Client::Service;

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

use Data::Dumper;



# These files don't contain header lines.
#
sub _noHeader { 1 }

sub _unverifiedFieldMap {
    {
        title => 'L',
        identifier => 'J',
    }
}


sub _fieldMap {
    {
        dateBegin        => 'F',
#        isrc             => 'J',
        artistName       => 'K',
#        trackName        => 'L',  # !!! this could be a track or an album...
        units            => 'M',
        price            => 'P',
        currencyCode     => 'Q',
        countryCode      => 'T',

        comments         => 'E', # !!! This is the 'Retail URL' column, which I am capturing for analysis.
    }
}


# JPK - Going to overload this to examine the line data, and determine whether this
# is a track or an album.
#
sub _isValidSaleRecord {
	my $self = shift;

    my $title = $self->_getByFieldName('title');
    return undef unless ($self->units && $title && $self->countryCode && $self->currencyCode);

    # Reset all the private fields.
    #
    $self->{_upc} = undef;
    $self->{_isrc} = undef;
    $self->{_trackTitle} = undef;
    $self->{_albumTitle} = undef;

    my $id = $self->_getByFieldName('identifier');
    if ($id =~ /^[a-zA-Z]{5}/)
    {
        # looks like a 'DTI' to me...
        #
        $self->{_isrc} = $id;
        $self->{_trackTitle} = $title;
    }
    elsif ($id =~ /^\d{11,13}$/)
    {
        # an ICPN, which we'll put in the UPC column.
        #
        $self->{_upc} = $id;
        $self->{_albumTitle} = $title;
    }
    else
    {
        # !!! At some point we might want to just skip bogus lines, but for now let's blow up.
        #
        die "ERROR - Unrecognised 'Digital Identifier' column value of '$id'";
    }
    

    return 1;
}


# These can be track or album sales.
# If the 'isrc' column looks like one of EMI's Digital Identifiers, we'll call it a track sale.
#

sub productType
{
    my ($self) = @_;
    return RPS::File::Sale::TYPE_TRACK if ($self->{_trackTitle});
    return RPS::File::Sale::TYPE_ALBUM if ($self->{_albumTitle});

    die "UNKNOWN PRODUCT TYPE - line " . $self->{linenum} . " track title = '".$self->{_trackTitle}."' album title = '".$self->{_albumTitle}."' whole line: " . Dumper($self->{line});

}

sub formatType  { RPS::File::Sale::FORMAT_DOWNLOAD}

sub trackName 
{
    my ($self) = @_;
    return $self->{_trackTitle};
}

sub albumName 
{
    my ($self) = @_;
    return $self->{_albumTitle};
}

sub isrc
{
    my ($self) = @_;
    return $self->{_isrc};
}

# !!! Also store the DTI in client_product_id
#
sub clientProductID
{
    my ($self) = @_;
    return $self->{_isrc};
}

sub upc
{
    my ($self) = @_;
    return $self->{_upc};
}


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