package RPS::Import::AltNet;

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';

# map version_num to the field order
my %field_map = (
    1 => {
        date_row  => 0,
        date_cell => 0,
        rate_tag  => 5,
        rate      => 7,
        album     => 1,
        track     => 2,
        upc       => 3,
        isrc      => 4,
        units     => 5,
        price     => 6,
        divide_by_units => 0,
    },
    2 => {
        date_row   => 2,
        date_cell  => 0,
        rate_tag   => 1,
        rate       => 4,
        track      => 0,
        album      => 1,
        upc        => 2,
        isrc       => 3,
        price      => 5,
        units      => 6,
        price_euro => 14,
        divide_by_units => 1,
    },
    3 => {
        date_row  => 0,
        date_cell => 0,
        rate_tag  => 6,
        rate      => 7,
        album     => 1,
        track     => 2,
        upc       => 3,
        isrc      => 4,
        units     => 5,
        price     => 6,
        divide_by_units => 0,
    },
    4 => {
        date_row  => 0,
        date_cell => 0,
        rate_tag  => 7,
        rate      => 9,
        album     => 5,
        track     => 6,
        artist    => 7,
        upc       => 3,
        isrc      => 4,
        units     => 9,
        price     => 8,
        divide_by_units => 0,
    },
);

#
# public methods
#

sub _importLines
{
    my $self = shift;
    my %args = @_;
    my $lines = $args{lines};

    return undef unless $lines;

    my $map = $field_map{$args{file}->VersionNum};

    my $dateSource = $lines->[$map->{date_row}][$map->{date_cell}];
    my ($dateBegin, $dateEnd) = _get_dates($dateSource);
    unless ($dateBegin && $dateEnd)
    {
        $self->errstr("unable to get dates from '$dateSource'");
        return undef;
    }
    print STDERR "using dates: $dateBegin - $dateEnd\n";

    my $rate = _get_rate($lines, $map->{rate_tag}, $map->{rate});
    unless ($rate)
    {
        $self->errstr("unable to get rate");
        return undef;
    }
    print STDERR "using rate: $rate\n";

    my $linenum = 1;
    foreach my $line(@$lines)
    {
        my $prodtype    = RPS::File::Sale::TYPE_TRACK;
        my $format      = RPS::File::Sale::FORMAT_DOWNLOAD;

        my $album       = $line->[$map->{album}];
        my $artist      = $line->[$map->{artist}];
        my $track       = $line->[$map->{track}];
        my $upc         = Common::Util::normalize_upc($line->[$map->{upc}]);
        my $isrc        = $line->[$map->{isrc}];
        my ($units)     = $line->[$map->{units}] =~ m/^(\d+)$/;
        my $price       = $line->[$map->{price}] * $rate;
        my $countryCode = exists $map->{price_euro} && $line->[$map->{price_euro}] ? 'EU' : 'US';

        $prodtype = RPS::File::Sale::TYPE_ALBUM if ($isrc eq "(album)");

        if ($album && $track && $units && $price)
        {
            $price /= $units if $map->{divide_by_units};

            if ($args{file}->VersionNum == 1 || $args{file}->VersionNum == 2 ||
                $args{file}->VersionNum == 3) {
                # cleanup
                $track =~ s/\.\w+$//; # strip the file extension
                $track =~ s/^(.*?)\s*-\s*//; # strip the artist
                $artist = $1;
                $album =~ s/^$artist//;
            }

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

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

            #$args{dumper}($sale);
            $self->_insertSale(sale => $sale);
        }
        $linenum++;
    }
    return $linenum;
}


#
# Private methods
#

sub _get_dates_from_filename
{
    my $fName = shift;

    return undef unless ($fName =~ m/.([a-z]+).(\d{4})\./i);
    my ($month, $year) = ($1, $2);
    $month = Decode_Month($month);

    return (
        sprintf("%04d-%02d-01", $year, $month), 
        sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month))
    ) if ($month && $year);
}

# date range should look something like 'From : MAR/2006 To : MAR/2006'
# or <Y>-<M>-1
# or <Label Name> MARCH 2006
sub _get_dates
{
    my $date = shift;
    my ($start_year, $start_month, $end_year, $end_month);

    if ($date =~ m/from.*to/i)
    {
        my ($start, $end) = split /\s*to\s*:\s*/i, $date;

        $start =~ s/\s+//g;
        $start =~ s/^From://i;
        ($start_month, $start_year) = split /\W/, $start;
        $start_month = Decode_Month($start_month) || return undef;

        $end =~ s/\s+//g;
        ($end_month, $end_year) = split /\W/, $end;
        $end_month = Decode_Month($end_month) || return undef;
    }
    elsif ($date =~ m/^(\d{4})\-(\d+)\-\d+$/) {
        $start_year = $end_year = $1;
        $start_month = $end_month = $2;
    }
    else
    {
        $date =~ m/\s+(\w+)\s+(\d+)$/;
        $start_year = $end_year = $2;
        $start_month = $end_month = Decode_Month($1);
    }

    return (
        sprintf("%04d-%02d-01", $start_year, $start_month), 
        sprintf("%04d-%02d-%02d", $end_year, $end_month, Days_in_Month($end_year, $end_month))
    );
}

sub _get_rate
{
    my ($lines, $tag, $val) = @_;

    foreach my $line(@$lines)
    {
        next unless ($line->[$tag] =~ /^revenue share$/i && $line->[$val] =~ /\d+/);
        return $line->[$val];
    }
    return undef;
}

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