package RPS::Import::PlayDigital;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

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

use lib '/app/tools/data_classes/lib';
use Client::Service;

my %field_map = (
    1 => {
        'upc'                => 0,
        'service_product_id' => 1,
        'isrc'               => 2,
        'units'              => 3,
        'currency'           => 10,
        'revenue'            => 12,
        'label'              => 13,
        'artist'             => 14,
        'track'              => 15,
        'country'            => 18,
        'format'             => 20,
        'date'               => 22,
    },
);

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 $fileName = $fileObj->OrigFileName;
    my $version  = $fileObj->VersionNum;

    return undef unless ( $lines && $fileName && $version );

    my $offsets = $field_map{$version};

    my %errors  = ();
    my $linenum = 2;

    my $distFee = 0;

    foreach my $line (@$lines) {
        if ( $linenum == 5 ) {
            $distFee = $line->[0];
            if ( $distFee =~ m/Transaction Costs (\d+\.\d+)%/ ) {
                $distFee = $1;
                $distFee = $distFee / 100;
            }
        }

        my $format;

        if ( $line->[ $offsets->{'format'} ] eq 'Download' ) {
            $format = RPS::File::Sale::FORMAT_DOWNLOAD;
        } elsif ( $line->[ $offsets->{'format'} ] eq 'Stream' ) {
            $format = RPS::File::Sale::FORMAT_STREAM;
        }

        my $prodtype = RPS::File::Sale::TYPE_TRACK;

        my $serviceID = $line->[ $offsets->{'service_product_id'} ];
        my $upc       = Common::Util::normalize_upc( $line->[ $offsets->{'upc'} ] );
        my $isrc      = Common::Util::normalize_isrc( $line->[ $offsets->{'isrc'} ] );
        my $artist    = $line->[ $offsets->{'artist'} ];
        my $track     = $line->[ $offsets->{'track'} ];
        my $label     = $line->[ $offsets->{'label'} ];
        my $units     = $line->[ $offsets->{'units'} ];
        my $country   = $line->[ $offsets->{'country'} ];

        my $currencyCode = $line->[ $offsets->{'currency'} ];

        my $revenue = $line->[ $offsets->{'revenue'} ];
        my $price;

        if ( $distFee > 0 ) {
            $revenue = $revenue * ( 1 - $distFee );
        }

        if ( $units > 0 ) {
            $price = ( $revenue / $units );
        }

        if ($price) {
            $price = sprintf( "%.8f", $price );
        }

        if ( $format && $units && ( $artist || $track ) ) {
            my ( $dateBegin, $dateEnd ) = _getDates( $line->[ $offsets->{date} ] );
            unless ( $dateBegin && $dateEnd ) {
                print STDERR "Couldn't get dates from " . $line->[ $offsets->{date} ] . "\n";
                $self->errstr( "couldn't get dates from " . $line->[ $offsets->{date} ] );
                return undef;
            }

            my $countryCode = $Common::Consts::COUNTRY_CODE{ lc $country };
            unless ( defined $countryCode || exists $errors{$country} ) {
                print STDERR "unknown country l:" . $linenum . " c: $country\n";
                $self->errstr( "unknown country l:" . $linenum . " c:" . $country );
            }

            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->artistName($artist);
            $sale->trackName($track);
            $sale->labelName($label);
            $sale->units($units);
            $sale->currencyCode($currencyCode);
            $sale->countryCode($countryCode);
            $sale->price($price);
            $sale->serviceProductID($serviceID);
            $sale->lineNum($linenum);

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

    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my ( $syear, $eyear, $smonth, $emonth, $passed_date, $dateBegin, $dateEnd );
    $passed_date = shift;
    print "$passed_date\n";
    if ( $passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/ ) {
        return ( $3 . "-" . sprintf( "%02d", $1 ) . "-01", $3 . "-" . sprintf( "%02d", $1 ) . "-" . Days_in_Month( $3, $1 ) );
    } elsif ( $passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/ ) {
        return ( $1 . "-" . sprintf( "%02d", $2 ) . "-01", $1 . "-" . sprintf( "%02d", $2 ) . "-" . Days_in_Month( $1, $2 ) );
    } elsif ( $passed_date =~ m/(\d{4})(\d{2})(\d{2})/ ) {
        return ( $1 . "-" . $2 . "-01", $1 . "-" . $2 . "-" . Days_in_Month( $1, $2 ) );
    }
    return undef;
}

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