package RPS::Import::WarpBleep;

use strict;

use Date::Calc qw(Days_in_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 base 'RPS::Import::Importer';

my %field_map = (
    1 => {
        date_begin => 1,
        date_end   => 2,
        label      => 3,
        svc_prodID => 4,
        prod_type  => 5,
        artist     => 6,
        title      => 7,
        currency   => 8,
        units      => 9,

        #exch_rate   => 14,
        price => 18,
    },
    2 => {
        date_begin => 1,
        date_end   => 2,
        label      => 3,
        svc_prodID => 4,
        prod_type  => 5,
        upc        => 6,
        isrc       => 7,
        artist     => 8,
        title      => 9,
        currency   => 10,
        units      => 11,

        #exch_rate   => 16,
        price => 20,
    },
);

#public methods

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

    my $fileObj  = $args{file};
    my $version  = $fileObj->VersionNum;
    my $fileName = $fileObj->OrigFileName;

    #my $version = $args{version}; # cmd-line testing
    #my $fileName = $args{OrigFileName};

    my $offsets = $field_map{$version};
    my $lines   = $args{lines};
    return 0 unless ($lines);

    my ( $dateBegin, $dateEnd ) = $self->_getDates($fileName);
    unless ( $dateBegin && $dateEnd ) {
        $self->errstr("couldn't get dates");
        print STDERR "fname: $fileName\n";
        return undef;
    }
    my $format = RPS::File::Sale::FORMAT_DOWNLOAD;

    my $linenum = 1;
    foreach my $line (@$lines) {
        my $label    = $line->[ $offsets->{label} ];
        my $svcProd  = $line->[ $offsets->{svc_prodID} ];
        my $artist   = $line->[ $offsets->{artist} ];
        my $title    = $line->[ $offsets->{title} ];
        my ($units)  = $line->[ $offsets->{units} ] =~ m/^(-?\d+)$/;
        my ($price)  = $line->[ $offsets->{price} ] =~ m/^(-?\d+\.?\d*)$/;
        my $currency = uc $line->[ $offsets->{currency} ];

        #my $exch_rate   = $line->[$offsets->{exch_rate}];

        if ( $units && defined $price && $artist && $title ) {
            my $dateB = Common::Util::normalize_date( $line->[ $offsets->{date_begin} ] );
            my $dateE = Common::Util::normalize_date( $line->[ $offsets->{date_end} ] );
            unless ( $dateB eq $dateBegin and $dateE eq $dateEnd ) {
                $self->warning();
                print STDERR "date diffs: row $dateB - $dateE and name $dateBegin - $dateEnd\n";
            }

            my ( $upc, $isrc );
            unless ( $version == 1 ) {
                $upc  = Common::Util::normalize_upc( $line->[ $offsets->{upc} ] );
                $isrc = Common::Util::normalize_isrc( $line->[ $offsets->{isrc} ] );
            }

            $price /= $units if $units;
            my ( $prodtype, $track, $album );
            if ( $line->[ $offsets->{prod_type} ] =~ /^t/i ) {
                $prodtype = RPS::File::Sale::TYPE_TRACK;
                $track    = $title;
            } else {
                $album    = $title;
                $prodtype = RPS::File::Sale::TYPE_ALBUM;
            }

            my $country =
                $currency eq 'GBP' ? 'GB'
              : $currency eq 'EUR' ? 'EU'
              :                      'EU';

            my $sale = RPS::Import::SaleRec->new();

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->labelName($label);
            $sale->serviceProductID($svcProd);
            $sale->upc($upc);
            $sale->isrc($isrc);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->trackName($track);
            $sale->units($units);
            $sale->price($price);
            $sale->countryCode($country);
            $sale->currencyCode('GBP');
            $sale->lineNum($linenum);

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

        #else { print STDERR "skip ($linenum) u: $units p: $price a: $artist t: $track\n" }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

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

    my ( $year, $month );
    if ( $fName =~ m/\b(\d{4})(\d\d)\D+/ ) {
        ( $year, $month ) = ( $1, $2 );
    } elsif ( $fName =~ m/(\d{4})\D+(\d\d)\D+/ ) {
        ( $year, $month ) = ( $1, $2 );
    }
    return undef unless ( $year && $month );

    return (
        Common::Util::normalize_date( join( '-', $year, $month, 1 ) ),
        Common::Util::normalize_date( join( '-', $year, $month, Days_in_Month( $year, $month ) ) ),
    );
}

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