package RPS::Import::TouchTunes;

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_LABEL    => 2;
use constant FIELD_VENDORID => 3;
use constant FIELD_TRACK    => 4;
use constant FIELD_ARTIST   => 5;
use constant FIELD_UNITS    => 6;
use constant FIELD_NETUNITS => 9;
use constant FIELD_PRICE    => 10;
use constant FIELD_PERIOD   => 12;
use constant FIELD_PRODTYPE => 13;

my %field_map = (
    1 => {
        'label'    => 2,
        'vendorid' => 3,
        'track'    => 4,
        'artist'   => 5,
        'units'    => 6,
        'netunits' => 9,
        'price'    => 11,
        'period'   => 12,
        'prodtype' => 13,
    },
    2 => {
        'label'    => 2,
        'vendorid' => 3,
        'track'    => 4,
        'artist'   => 5,
        'price'    => 6,
        'units'    => 8,
        'netunits' => 8,
        'period'   => 9,
        'prodtype' => 10,
    },
);

my $offsets;

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};
    my $fileObj  = $args{file};
    my $version  = $self->_version();
    my $fileName = $fileObj->OrigFileName;

    #my $fileName = $args{OrigFileName};

    $offsets = $field_map{$version};

    if ( $lines && $fileName ) {
        my $linenum = 1;
        foreach my $line (@$lines) {
            if ( $linenum > 1 ) {

                my $period = $line->[ $offsets->{'period'} ];
                $period .= "q" if $period !~ /q/i;
                my ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $period, type => 'quarter' );

                my $prodtype = RPS::File::Sale::TYPE_TRACK;
                my $format   = RPS::File::Sale::FORMAT_JUKEBOX;
                my $vendorID = $line->[ $offsets->{'vendorid'} ];
                my $artist   = $line->[ $offsets->{'artist'} ];
                my $track    = $line->[ $offsets->{'track'} ];
                my $label    = $line->[ $offsets->{'label'} ];

                my $net_units = $line->[ $offsets->{'netunits'} ];
                my $units = $line->[ $offsets->{'units'} ];

                my $format_type = $line->[ $offsets->{'prodtype'} ] || "";
                if ( ($format_type !~ /^coin[ -]op(?:erated)?$/i) && ($format_type !~ /^background(?: music)?$/i) ) {
                    $self->fail("Could not parse format type from '$format_type'");
                }
                if ( $format_type =~ m/^coin[ -]op(?:erated)?$/i ) {
                    ($units) = $net_units =~ m/^(-?\d+)$/;
                    ($units) = $units =~ m/^(-?\d+)$/ unless $units;
                }
                elsif ( $format_type =~ m/^background(?: music)?$/i ) {
                    ($units) = $units =~ m/^(-?\d+)$/;
                    $format = RPS::File::Sale::FORMAT_BACKGROUNDMUSIC;
                }

                my ($price) = $line->[ $offsets->{'price'} ] =~ m/^(-?\d*.?\d+)$/;

                if ( $price < 0 ) {
                    $price *= -1;
                    $units *= -1;
                }

                if ( $units && $price && $artist && $track ) {
                    unless ( $dateBegin && $dateEnd ) {
                        my $l = join( '+', @$line );
                        print STDERR "skip $l ($linenum)\n";
                        $self->errstr("couldn't get dates");
                    }
                    my $sale = RPS::Import::SaleRec->new();

                    $sale->productType($prodtype);
                    $sale->formatType($format);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->serviceProductID($vendorID);
                    $sale->artistName($artist);
                    $sale->trackName($track);
                    $sale->labelName($label);
                    $sale->units($units);
                    $sale->price($price/$units);
                    $sale->lineNum($linenum);
                    $sale->countryCode('US');
                    $sale->serviceID(Client::Service::DSP_TOUCHTUNES);

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

    return $retval;
}

sub _getDates {
    my ($self, %attr) = @_;

    my $period = $attr{date_begin} || '';

    my ( $dateBegin, $dateEnd );
    my ( $quarter, $year ) = $period =~ /^Q(1|2|3|4) ((1|2)\d\d\d)$/;
    if ( $quarter && $year ) {
        my $month;
        if ( $quarter == 1 ) {
            $month = 1;
        } elsif ( $quarter == 2 ) {
            $month = 4;
        } elsif ( $quarter == 3 ) {
            $month = 7;
        } else {
            $month = 10;
        }

        $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
        $dateEnd = sprintf( "%04d-%02d-%02d", $year, $month + 2, Days_in_Month( $year, $month + 2 ) );
    } elsif ( $period =~ /^(\d{4})(\d{2}).?$/ ) {
        return
            sprintf( "%04d-%02d-%02d", $1, $2, 1 ),
            sprintf( "%04d-%02d-%02d", $1, $2, Days_in_Month($1, $2) );
    } else {
        return $self->SUPER::_getDates(%attr);
    }

    return ( $dateBegin, $dateEnd );
}

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