package RPS::Import::Juno;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days);

use lib '/app/tools/common/lib';
use Common::Consts qw(%COUNTRY_TO_CODE %COUNTRY_CODE);
use Common::Country;

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 => {
        label      => 0,
        date       => 1,
        product_id => 3,
        upc        => 4,
        album      => 5,
        track      => 6,
        isrc       => 9,
        artist     => 11,
        units      => 13,
        country    => 15,
        price      => 16,
        refund     => 18,
    },
    2 => {
        date       => 0,
        label      => 1,
        product_id => 3,
        upc        => 4,
        album      => 5,
        artist     => 6,
        track      => 7,
        mix        => 8,
        isrc       => 10,
        price      => 13,
        country    => 15,
        refund     => 16,
    },
);

my %countries = (
    'trinidad & tobago' => 'trinidad and tobago',
    'guiana (fr.)'      => 'french guiana',
);

#public methods

sub _importLines {
    my $self     = shift;
    my %args     = @_;
    my $fileObj  = $args{file};
    my $version  = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();

    #my $version = $args{version}; # cmd-line testing
    #my $fileName = $args{OrigFileName}; # cmd-line testing
    my $sheet_count = 0;
    return undef unless ( defined $args{sheets} && defined $version );

    my $offsets     = $field_map{$version};
    my $sheet_names = $args{sheet_names};
    my $linenum     = 1;
    my %errors;

    my $currency = "GBP";

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $linenum = 1;
        foreach my $line (@$sheet) {
            my $artist     = $line->[ $offsets->{artist} ];
            my $isrc       = $line->[ $offsets->{isrc} ];
            my $upc        = $line->[ $offsets->{upc} ];
            my $title      = $line->[ $offsets->{track} ];
            my $album      = $line->[ $offsets->{album} ];
            my $label      = $line->[ $offsets->{label} ];
            my $product_id = $line->[ $offsets->{product_id} ];
            my $price      = $line->[ $offsets->{price} ];
            $price =~ s/£//;
            my $country_name = lc $line->[ $offsets->{country} ];
            my $refund       = lc $line->[ $offsets->{refund} ];
            my $country;

            my $units;

            if ( $version == 2 ) {
                $units = 1;
            } else {
                $units = $line->[ $offsets->{units} ];
                $price = ( $units != 0 ) ? ( $price / $units ) : 0;
                $price = abs $price;
            }

            if ( $refund =~ /refund/i ) {
                $units *= -1;
            }

            if ( $units && $price && $artist && $title ne "Track" ) {

                my $_countryName = $countries{$country_name} || $country_name;

                my $countryObj = Common::Country->Get($_countryName) || die "Unknown country name '$country_name' line: " . $linenum--;
                $country = $countryObj->alpha2();

                my @dateTypes = ( 'iso', 'eur' );
                my ( $dateBegin, $dateEnd ) =
                  $self->_getDates( date_begin => $line->[ $offsets->{date} ], type => \@dateTypes );

                unless ( defined $dateBegin && defined $dateEnd ) {
                    $self->errstr( "Couldn't get dates from " . $line->[ $offsets->{date} ] );
                    return undef;
                }

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

                if ( $title eq "Entire Release" || $title eq "" ) {
                    $prodtype = RPS::File::Sale::TYPE_ALBUM;
                } elsif ( $version == 2 ) {

                    # For tracks in version 2, we'll add the mix to the title, if there is one.
                    #
                    my $mix = $line->[ $offsets->{mix} ];
                    if ($mix) {
                        $title .= " (" . $mix . ")";
                    }
                }

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

                if ( $refund =~ /refund/i ) {
                    $units *= -1 if ( $units > 0 );
                    $price *= -1 if ( $price < 0 );
                }

                $sale->productType($prodtype);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->upc($upc) if ( $upc ne "" );
                $sale->isrc($isrc);
                $sale->labelName($label);
                $sale->artistName($artist);
                $sale->albumName($album) if ( $album ne "" );
                $sale->trackName($title) if ( $title ne "" && $title ne "Entire Release" );
                $sale->serviceProductID($product_id);
                $sale->formatType($format);
                $sale->units($units);
                $sale->price($price);
                $sale->countryCode($country);
                $sale->currencyCode($currency);
                $sale->lineNum($linenum);

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

            #else { print STDERR "Skipping line: " . $linenum . " : " . join(",",@$line) . "\n"; }
            $linenum++;
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

#sub _getDates
#{
#	my $self = shift;
#	my $passed_date = shift;
#    $passed_date =~ s/\s.*$// if($passed_date =~ /\s/);
#    my ($day,$month,$year);
#    if($passed_date =~ /(\d+)\D(\d+)\D(\d{4})/) {
#        $passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/;
#        $month = $2;
#        $year = $3;
#    }
#    elsif($passed_date =~ /(\d{4})\D(\d+)\D(\d+)/) {
#        $passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/;
#        $year = $1;
#        $month = $2;
#    }
#    my $dateBegin = sprintf("%04d-%02d-%02d", $year, $month, 1);
#    my $dateEnd   = sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month));
#    return ($dateBegin, $dateEnd);
#    return undef;
#}

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