package RPS::Import::BuyMusic;

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::Import::Importer;
use RPS::File::Sale;
use base 'RPS::Import::Importer';

use constant FIELD_TYPE  => 0;
use constant FIELD_UPC   => 1;
use constant FIELD_ISRC  => 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 $fileName = $args{file}->OrigFileName;
    my ( $dateBegin, $dateEnd ) = _get_dates($fileName);

    unless ( $dateBegin && $dateEnd ) {
        $self->errstr("unable to get dates from file name ($fileName)");
        return undef;
    }

    #print STDERR "using dates: $dateBegin - $dateEnd\n";

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

        my $prodtype =
            lc( $line->[FIELD_TYPE] ) eq 'a' ? RPS::File::Sale::TYPE_ALBUM
          : lc( $line->[FIELD_TYPE] ) eq 't' ? RPS::File::Sale::TYPE_TRACK
          :                                    '';
        my $upc     = Common::Util::normalize_upc( $line->[FIELD_UPC] );
        my $isrc    = $line->[FIELD_ISRC];
        my ($units) = $line->[FIELD_UNITS] =~ m/^(\d+)$/;
        my $price   = $line->[FIELD_PRICE];

        if ( $prodtype && $upc && $units && $price ) {
            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->units($units);
            $sale->price($price);
            $sale->lineNum($linenum);

            $self->_insertSale( sale => $sale );
        }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _get_dates {
    my $fName = shift;

    return undef unless ( $fName =~ m/_(\d{4})(\d\d)\d\d\./i );
    my ( $year, $month ) = ( $1, $2 );

    if ( $month == 1 ) {
        $year--;
        $month = 12;
    } else {
        $month--;
    }

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

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