package RPS::Import::Theta;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

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

use constant DATE_COL => 1;
use constant DATE_ROW => 5;  ## looks like it should be 6 in the file, but first line is weird

use constant CARRIERS_ROW => 4;
use constant CARRIERS_COL => 1;

use constant FIELD_HEADER    => 9;

use constant FIELD_TRACK     => 0;
use constant FIELD_ARTIST    => 1;
use constant FIELD_VENDORID  => 2;
use constant FIELD_UNITS     => 3;
use constant FIELD_PRICE     => 4;

#
# public methods
#

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

    return undef unless ($lines);
    my $version = $args{file}->VersionNum();
    #my $version = $args{version}; # cmd-line testing

    my ($dateBegin, $dateEnd) = _get_dates($lines->[DATE_ROW][DATE_COL]);

    unless ($dateBegin && $dateEnd)
    {
        $self->errstr("couldn't get dates");
        print STDERR "date cell: ".($lines->[DATE_ROW][DATE_COL])."\n";
        return undef;
    }

    my $distributors = ();
    my ($unitPrice, $serviceID);
    if ($version == 2)
    {
        ($distributors, $unitPrice) = $self->_parse_header($lines->[FIELD_HEADER]);
        unless (ref $distributors eq 'ARRAY' and scalar @$distributors > 0)
        {
            $self->errstr("couldn't get services");
            return undef;
        }
    }
    else
    {
        unless ($serviceID = $self->getServiceID($lines->[CARRIERS_ROW][CARRIERS_COL]))
        {
            $self->warning();
            print STDERR "can't map service: ", $lines->[CARRIERS_ROW][CARRIERS_COL], "\n";
        }
    }

    my $prodtype    = RPS::File::Sale::TYPE_TRACK;
    my $format      = RPS::File::Sale::FORMAT_RINGTONE;
    my $currency    = 'JPY';
    my $country     = 'JP';
    my $conv_rate   = 0;

    my $linenum = 1;

    foreach my $line (@$lines)
    {
        my $vendor_id   = $line->[FIELD_VENDORID];
        my $artist      = $line->[FIELD_ARTIST];
        my $track       = $line->[FIELD_TRACK];
        my ($units)     = $line->[FIELD_UNITS] =~ m/^(\d+)$/;
        my ($price)     = $line->[ $version == 2 ? $unitPrice : FIELD_PRICE ] =~ m/^(\d+\.?\d*)$/;
        ## price is given as price-per-unit

        if ($artist && $track && $price)
        {
            my $sale = RPS::Import::SaleRec->new();

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->serviceProductID($vendor_id);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->artistName($artist);
            $sale->trackName($track);
            $sale->price($price);
            $sale->countryCode($country);
            $sale->currencyCode($currency);
            $sale->lineNum($linenum);

            if ($version == 2)
            {
                foreach my $dist(@$distributors)
                {
                    next unless ($line->[ $dist->{offset} ] > 0);
                    $sale->units($line->[ $dist->{offset} ]);
                    $sale->serviceID($dist->{serviceID});

                    #$args{dumper}($sale); ## for cmd-line testing
                    $self->_insertSale(sale => $sale);
                }
            }
            else
            {
                $sale->units($units);
                $sale->serviceID($serviceID);

                #$args{dumper}($sale); ## for cmd-line testing
                $self->_insertSale(sale => $sale);
            }
        }
        #else { print "skip ". join(',', @$line) . "\n"; }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _get_dates
{
    my $cell = shift;

    return undef unless ($cell =~ m/^(.*),\s+(\d{4})$/);
    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);
}

sub _parse_header
{
    my $self = shift;
    my $header = shift;

    my @dist = ();
    my $i = FIELD_VENDORID;

    while (lc $header->[++$i] ne 'unit price')
    {
        $header->[$i] =~ m/^(.+)\sDownloads/;
        if (my $serviceID = $self->getServiceID($1))
        {
            push @dist, {
                serviceID => $serviceID,
                offset => $i,
            };
        }
        else
        {
            $self->warning();
            print STDERR "can't map service: $1\n";
        }
    }

    return (\@dist, $i);
}

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