package RPS::Import::eMusicMech;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

#private constants
use constant FIELD_ALBUM    => 1;
use constant FIELD_VENDORID => 2;
use constant FIELD_TRACK    => 3;
use constant FIELD_LABEL    => 4;
use constant FIELD_UNITS    => 6;
use constant FIELD_PRICE    => 7;

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

#public methods

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

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

    return undef unless ($lines);

    my ( $dateBegin, $dateEnd ) = $self->_getDates($fileName);

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

        my $vendorid = $line->[FIELD_VENDORID];
        my $album    = $line->[FIELD_ALBUM];
        my $track    = $line->[FIELD_TRACK];
        my $label    = $line->[FIELD_TRACK];
        my ($units)  = $line->[FIELD_UNITS] =~ m/^(-?\d+)$/;
        my ($price)  = $line->[FIELD_PRICE] =~ m/^(\d*\.?\d*)$/;

        $price = ( $units != 0 ) ? ( $price / $units ) : 0;

        if ( $prodtype && $dateBegin && $units && $price && $album && $track ) {
            my $sale = RPS::Import::SaleRec->new();

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->serviceProductID($vendorid);
            $sale->albumName($album);
            $sale->trackName($track);
            $sale->labelName($label);
            $sale->units($units);
            $sale->price($price);
            $sale->lineNum($linenum);
            $sale->countryCode('US');

            $self->_insertSale( sale => $sale );
            ##$args{dumper}($sale);  ## for cmd-line testing
        }
        $linenum++;
    }

    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $self = shift;
    my $date = shift;
    my ( $beginDate, $endDate );

    $date =~ m/\s*q([1234])(\d{2})\s*/;
    my $qtr  = $1;
    my $year = $2 + 2000;

    if ( $qtr == 1 ) {
        $beginDate = $year . "-01-01";
        $endDate = $year . "-03-" . Days_in_Month( $year, 3 );
    } elsif ( $qtr == 2 ) {
        $beginDate = $year . "-04-01";
        $endDate = $year . "-06-" . Days_in_Month( $year, 6 );
    } elsif ( $qtr == 3 ) {
        $beginDate = $year . "-07-01";
        $endDate = $year . "-09-" . Days_in_Month( $year, 9 );
    } elsif ( $qtr == 4 ) {
        $beginDate = $year . "-10-01";
        $endDate = $year . "-12-" . Days_in_Month( $year, 12 );
    }

    return ( $beginDate, $endDate );
}

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