package RPS::Import::Sprint;

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_DATE        => 3;
use constant FIELD_DESCRIPTION => 4;
use constant FIELD_UNITS       => 7;
use constant FIELD_PRICE       => 8;

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 $retval = undef;
    my $lines  = $args{lines};

    if ($lines) {

        #my ($dateBegin, $dateEnd) = $self->_getDates($lines);
        #punt on this for now
        my ( $dateBegin, $dateEnd ) = ( '2005-01-01', '2005-01-31' );

        if ( $dateBegin && $dateEnd ) {
            my $linenum = 1;
            foreach my $line (@$lines) {
                if ( $linenum > 1 ) {
                    my $prodtype = RPS::File::Sale::TYPE_TRACK;
                    my $format   = RPS::File::Sale::FORMAT_RINGTONE;
                    my ( $track, $artist ) = split( '-', $line->[FIELD_DESCRIPTION] );
                    my ($units) = $line->[FIELD_UNITS] =~ m/^(-?\d+)$/;
                    my ($price) = $line->[FIELD_PRICE] =~ m/^(\d*\.\d*)$/;

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

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

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

    return $retval;
}

#
# Private methods
#

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

    my $dateBegin;
    my $dateEnd;

    my %months = (
        Jan => 1,
        Feb => 2,
        Mar => 3,
        Apr => 4,
        May => 5,
        Jun => 6,
        Jul => 7,
        Aug => 8,
        Sep => 8,
        Oct => 10,
        Nov => 11,
        Dec => 12
    );

    my ( $month, $year ) = $lines->[3]->[0] =~ m/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w* (20\d\d)/i;

    if ( $year && $month ) {
        $month = $months{$month};

        $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
        $dateEnd = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
    }

    return ( $dateBegin, $dateEnd );
}

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