package RPS::Import::BeatsDigital;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_Month);

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

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';

my %fieldMap = (
    1 => {
        date        => 1,
        product     => 2,
        catalog     => 3,
        code        => 4,
        label       => 5,
        artist      => 6,
        title       => 7,
        mix         => 8,
        units       => 10,
        price       => 12,
    },
    2 => {
        date        => 1,
        product     => 2,
        catalog     => 3,
        code        => 4,
        label       => 5,
        artist      => 6,
        title       => 7,
        mix         => 8,
        units       => 10,
        price       => 12,
        country     => 13,
    },
    3 => {
        date        => 1,
        product     => 2,
        catalog     => 3,
        upc         => 4,
        code        => 5,
        label       => 6,
        artist      => 7,
        title       => 8,
        mix         => 9,
        units       => 11,
        price       => 14,
        country     => 15,
    },
);

my %product_map = (
    single      => RPS::File::Sale::TYPE_TRACK,
    album       => RPS::File::Sale::TYPE_ALBUM,
);


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

    return undef unless (defined $args{sheets} && defined $version);

	my $offsets     = $fieldMap{$version};
    my $sheet_names = $args{sheet_names};
    my $linenum     = 1;
    my ($dateBegin,$dateEnd);
	my $headerFound;

    foreach my $sheet(@{ $args{sheets} }) {
        $linenum    = 1;
        if($sheet_names->[$sheet_count] !~ /total/i) {

		    $headerFound = undef;

            foreach my $line (@$sheet) {
				unless( $headerFound ) {

					$headerFound = 1 if( $line->[$offsets->{date}] =~ /^date$/ );
					$linenum++;
					next;
				}

                my ($f_date) = split( /\s/, $line->[$offsets->{date}] );

				#($dateBegin,$dateEnd)   = _getDates($line->[$offsets->{date}]);
                ($dateBegin,$dateEnd)   = $self->_getDates(date_begin => $f_date);

                my $country;
                my $product             = $product_map{$line->[$offsets->{product}]};
                my $artist              = $line->[$offsets->{artist}];
                my $format              = RPS::File::Sale::FORMAT_DOWNLOAD;
                my $catalog             = $line->[$offsets->{catalog}];
                my $upc                 = $line->[$offsets->{upc}];
                my $isrc_upc            = $line->[$offsets->{code}];
                my $label               = $line->[$offsets->{label}];
                my $title               = $line->[$offsets->{title}];
                my $currency            = "GBP";
                my $price               = $line->[$offsets->{price}];
                my $units               = $line->[$offsets->{units}];
                $price                  /= $units if($units != 0);

                if ($artist || $title || $label ) {

                    unless (defined $dateBegin && defined $dateEnd) {
                        die "Couldn't get dates from: $f_date (line: $linenum)";
                    }

                    if(defined $offsets->{country}){
                        $line->[$offsets->{country}] =~ s/\s+\(.*//;
						$country = $line->[$offsets->{country}];

                        if( $country && length($country) > 2 ) {
						    $country = $Common::Consts::COUNTRY_CODE{lc $line->[$offsets->{country}]};
						}

                        if(!$country){
                            print STDERR "Unknown country ".
                            $line->[$offsets->{country}]." at linenum: $linenum\n";
                            $self->errstr("Unknown country ".$line->[$offsets->{country}].
                            " at linenum: $linenum\n");
                            return undef;
                        }
                    }
                    else{
                        $country = "GB";
                    }

					if($product eq RPS::File::Sale::TYPE_ALBUM) {
						$upc = $isrc_upc;
					}


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

                    $sale->mediaType(2) if($format =~ /video/i);
                    $sale->productType($product);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->labelName($label);
                    $sale->artistName($artist);
                    $sale->trackName($title) if($product eq RPS::File::Sale::TYPE_TRACK);
                    $sale->albumName($title) if($product eq RPS::File::Sale::TYPE_ALBUM);
                    $sale->formatType($format);
                    $sale->serviceProductID($catalog) if(defined $offsets->{catalog});
                    $sale->isrc(Common::Util::normalize_isrc($isrc_upc)) if($product eq RPS::File::Sale::TYPE_TRACK);
                    $sale->upc(Common::Util::normalize_upc($upc));
                    $sale->units($units);
                    $sale->price($price);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);

                    $self->_insertSale(sale => $sale);
                }
                #else { print STDERR "skip s:".$sheet_names->[$sheet_count]." l:" . $linenum . " - u:".$units." p:".$price." t:".$title." c:".$catalog ."\n"; }
                $linenum++;
            }
        }
        $sheet_count++;
    }
	return $linenum;
}

#
# Private methods
#


sub OLD_getDates
{
    die;
	my ($syear,$eyear,$smonth,$emonth,$passed_date,$dateBegin,$dateEnd);
    $passed_date = shift;

    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));
    }

    return undef;
}

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