package RPS::Import::KarmaDownload;

use strict;


use Date::Calc qw(Days_in_Month Decode_Month);

use lib '/app/tools/common/lib';
use Common::Util;

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

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

my %field_map = (
    1 => {
        label           => 0,
        artist          => 1,
        title           => 2,
        type            => 3,
        upc_isrc        => 4,
        units           => 6,
        currency        => 8,
        country         => 9,
        price           => 11,
        line_date       => 4,
        field_conv_rate => 10,
    },
    2 => {
        label           => 0,
        artist          => 1,
        title           => 2,
        type            => 3,
        upc_isrc        => 4,
        units           => 6,
        currency        => 8,
        country         => 9,
        price           => 12,
        field_conv_rate => 11,
    },
    3 => {
        label           => 0,
        artist          => 1,
        title           => 2,
        type            => 3,
        upc_isrc        => 4,
        units           => 6,
        currency        => 8,
        country         => 9,
        price           => 14,
        field_conv_rate => 13,
    },
    4 => {
        label           => 11,
        artist          => 0,
        title           => 1,
        type            => 2,
        upc_isrc        => 11,
        units           => 4,
        currency        => 6,
        country         => 7,
        price           => 9,
        field_conv_rate => 8,
    },
    5 => {
        label           => 0,
        artist          => 1,
        title           => 2,
        type            => 3,
        upc_isrc        => 4,
        units           => 6,
        currency        => 8,
        country         => 9,
        price           => 11,
        field_conv_rate => 10,
    },
);


my $reporting_currency = "GBP";

#
# public methods
#

sub _importLines
{
    my $self = shift;
    my %args = @_;
    my $lines = $args{lines};
    my $sheets = $args{sheets};
    my $version = $self->_version();
    my $fileName = $args{file}->OrigFileName;

    my $offsets = $field_map{$version};

    return undef unless $lines;

    my ($dateBegin, $dateEnd);
    ($dateBegin,$dateEnd) = _get_dates($version,$lines->[$offsets->{line_date}]) if($version==1);
    ($dateBegin,$dateEnd) = _get_dates($version,$fileName) if($version!=1);
    
    unless($dateBegin && $dateEnd){
        if($fileName =~ /\d{4}\D\d{2}\D\d{2}/){
            ($dateBegin, $dateEnd) = 
            $self->SUPER::_getDates(date_begin=>$fileName, type=>"iso");
        }
    }

    unless ($dateBegin && $dateEnd) {
        $self->errstr("couldn't get dates from " . $lines->[$offsets->{line_date}]) if($version==1);
        $self->errstr("couldn't get dates from " . $fileName) if($version!=1);
        print STDERR "Couldn't get dates\n";
        return undef;
    }

    my $conv_rate = _get_conversion_rate($offsets->{field_conv_rate},$lines);
    unless ($conv_rate) {
        $self->errstr("couldn't get conversion rate");
        return undef;
    }

    my $linenum;
    $linenum = 13 if($version!=1 || $version!=5);
    $linenum = 1 if($version==1 || $version==5);
    foreach my $line(@$lines)
    {
        my $convRate = 0;
        my $format   = RPS::File::Sale::FORMAT_DOWNLOAD;
        my $prodtype;
        $prodtype = RPS::File::Sale::TYPE_ALBUM if($line->[$offsets->{type}] =~ /album/i);
        $prodtype = RPS::File::Sale::TYPE_ALBUM if($line->[$offsets->{type}] =~ /compilation/i);
        $prodtype = RPS::File::Sale::TYPE_TRACK if($line->[$offsets->{type}] =~ /track/i);

        my ($album, $track, $upc, $isrc);
        if ($prodtype eq RPS::File::Sale::TYPE_ALBUM)
        {
            $upc = Common::Util::normalize_upc($line->[$offsets->{upc_isrc}]);
            $album = $line->[$offsets->{title}];
        }
        elsif ($prodtype eq RPS::File::Sale::TYPE_TRACK)
        {
            $isrc = $line->[$offsets->{upc_isrc}];
            $track = $line->[$offsets->{title}];
        }

        my $label    = $line->[$offsets->{label}];
        my $artist   = $line->[$offsets->{artist}];
        my $country  = $line->[$offsets->{country}];
        my $currency = $line->[$offsets->{currency}];
        my $units    = $line->[$offsets->{units}];
        my $price    = $line->[$offsets->{price}];

        if ($units && $price && ($track || $album))
        {
            $price /= $units if($units>1);

            #if ($currency ne $reporting_currency)
            #{
            #    #$price /= $conv_rate;
            #    $currency = $reporting_currency;
            #}
            if($currency ne "USD" && $conv_rate ne "") {
                $currency = "USD";
                $price *= $conv_rate;
            }

            my $sale = RPS::Import::SaleRec->new();

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->upc($upc);
            $sale->isrc($isrc);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->trackName($track);
            $sale->labelName($label);
            $sale->currencyCode($currency);
            $sale->countryCode($country);
            $sale->units($units);
            $sale->price($price);
            $sale->lineNum($linenum);

            $self->_insertSale(sale => $sale);
        }
        #else { print STDERR "Skipping l:".$linenum." u:". $units . " p:".$price." a:".$artist." t:".$track." m:".$album." f:".$format." p:".$prodtype."\n"; }
        $linenum++;
    }
    return $linenum;
}


#
# Private methods
#

sub _get_dates
{
    my $version = shift;
    if($version == 1) {
        my $line = shift;
        my $date_range = $line->[1];

        return undef unless ($line->[0] eq 'Period' and $date_range =~ s/\s(\d{4})$//);

        my $year = $1;
        my ($start_date, $end_date) = split /\s-\s/, $date_range;

        $start_date =~ m/\s(\w+)$/;
        my $start_month = Decode_Month($1);

        $end_date =~ m/\s(\w+)$/;
        my $end_month = Decode_Month($1);

        return (sprintf("%04d-%02d-01", $year, $start_month), sprintf("%04d-%02d-%02d", $year, $end_month, Days_in_Month($year, $end_month)));
    }
    elsif($version!=1) {
        my $passed_date = shift;
        if($passed_date =~ m/(\d{4}) (\d+)\-(\d+)/) {
            my $year = $1;
            my $month_start = $2;
            my $month_end = $3;
            my $date_begin = $year."-".$month_start."-01";
            my $date_end = $year."-".$month_end."-".Days_in_Month($year,$month_end);
            return ($date_begin,$date_end);
        }
    }
    return undef;
}

sub _get_conversion_rate
{
    my $field = shift;
    my $rows = shift;
    foreach my $row(@$rows)
    {
        if($row->[$field] =~ m/USD conversion of \$(\d+\.\d+)\s/) {
            return $1;
        }
        elsif($row->[$field] =~ m/US\$ conversion of \$(\d+\.\d+) /) {
            return $1;
        }
    }
}

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