package RPS::Import::OmStream;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

use constant FIELD_TOTAL            => 7;
use constant FIELD_PAID             => 8;

use constant FIELD_TITLE            => 0;
use constant FIELD_UNITS            => 1;
use constant FIELD_ARTIST           => 2;
use constant FIELD_LABEL            => 3;
use constant FIELD_PRODTYPE         => 4;
use constant FIELD_PRICE            => 5;

#public methods

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

    my $fileObj = $args{file};
    my $fileName = $fileObj->OrigFileName;
    #my $fileName = $args{OrigFileName}; # for cmd-line testing

    my $lines = $args{lines};
    return 0 unless ($lines);

    my ($dateBegin, $dateEnd) = $self->_getDates($fileName);
    unless ($dateBegin && $dateEnd)
    {
        $self->errstr("couldn't get dates");
        print STDERR "fname: $fileName\n";
        return undef;
    }

    my $rate = $self->_getRate($lines);
    unless ($rate)
    {
        $self->errstr("couldn't get rate");
        return undef;
    }

    my $format = RPS::File::Sale::FORMAT_DOWNLOAD;
    my $linenum = 1;
    foreach my $line(@$lines)
    {
        my ($track, $album);
        my $prodType = lc $line->[FIELD_PRODTYPE];

        my $artist      = $line->[FIELD_ARTIST];
        my ($units)     = $line->[FIELD_UNITS] =~ m/^(\d+)$/;
        my ($price)     = $line->[FIELD_PRICE] =~ m/^(-?\d+\.\d+)$/;
        my $label       = $line->[FIELD_LABEL];

        if ($format && $price && $units && $artist)
        {
            if ($prodType eq 'track')
            {
                $prodType = RPS::File::Sale::TYPE_TRACK;
                $track = $line->[FIELD_TITLE];
            }
            elsif ($prodType eq 'album')
            {
                $prodType = RPS::File::Sale::TYPE_ALBUM;
                $album = $line->[FIELD_TITLE];
            }
            else
            {
                $self->errstr('unknown product type');
                print STDERR "prod-type: $prodType\n";
                return undef;
            }

            $price *= $rate;

            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->trackName($track);
            $sale->units($units);
            $sale->price($price);
            $sale->labelName($label);
            $sale->lineNum($linenum);
            $sale->countryCode('US');
    
            #$args{dumper}($sale);  ## for cmd-line testing
            $self->_insertSale(sale => $sale);
        }#else { print STDERR "skip: $linenum f: $format p: $price u: $units a: $artist\n"; }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates
{
    my $self = shift;
    my $fName = shift;

    return undef unless ($fName =~ m/\D(\d)(st|nd|rd|th)qua\D+(\d\d\d\d)\D/i);
    my ($month, $year) = ($1 * 3, $3);

    return (
        Common::Util::normalize_date(join('-', $year, $month-2,1)),
        Common::Util::normalize_date(join('-', $year, $month, Days_in_Month($year, $month))),
   );
}

sub _getRate
{
    my $self = shift;
    my $lines = shift;

    # unfortunately, we have to iterate the entire file to find the totals at the end
    # and calculate the rate
    foreach my $line(@$lines)
    {
        if ($line->[FIELD_PAID] =~ m/^(-?\d+\.\d+)$/)
        {
            my $paid = $1;
            my ($total) = $line->[FIELD_TOTAL] =~ m/^(-?\d+\.\d+)$/;

            return $paid / $total if ($total && $total != 0);
            last;
        }
    }

    return undef;
}

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