package RPS::Import::RealTones;

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

use constant FIELD_PRODUCTID => 3;
use constant FIELD_ARTIST    => 4;
use constant FIELD_TRACK     => 5;
use constant FIELD_UNITS     => 8;
use constant FIELD_PRICE     => 13;

#
# public methods
#

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

    my ( $dateBegin, $dateEnd ) = _get_dates( $sheets->[0][0][0] );

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

    my $sheetCount = 0;
    my $linenum    = 1;

    foreach my $sheet (@$sheets) {
        next if ( $sheetCount++ == 0 );
        foreach my $line (@$sheet) {
            my $prodtype = RPS::File::Sale::TYPE_TRACK;
            my $format   = RPS::File::Sale::FORMAT_DOWNLOAD;

            my $product_id = $line->[FIELD_PRODUCTID];
            my $artist     = $line->[FIELD_ARTIST];
            my $track      = $line->[FIELD_TRACK];
            my ($units)    = $line->[FIELD_UNITS] =~ m/^(\d+)$/;
            my ($price)    = $line->[FIELD_PRICE] =~ m/^(\d+\.?\d*)$/;

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

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

                #$args{dumper}($sale);
                $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+(\w+)\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 );
}

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