package RPS::Import::CherryRed;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);
use Spreadsheet::ParseExcel;

use lib '/app/tools/common/lib';
use Common::Util qw(normalize_date);
use Common::Consts;
use Common::RSMath qw(round);

use lib '/app/tools/data_classes/lib';

my %field_map = (
    1 => {
        service_product_id  => 36,
        jumble              => 7,
        date                => 9,
        price               => 15,
        fee                 => 14,
        country             => 28,
        currency            => 34,
        podcast_check       => 37,
    },
);

my %service_map = (

);

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 $fileObj = $args{file};
    my $version = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    my $offsets = $field_map{$version};
    my $sheet_count = 0;
    my $linenum;
    return undef unless (defined $args{sheets} && defined $version);

    my $sheet_names = $args{sheet_names};

    foreach my $sheet(@{ $args{sheets} }) {
        $linenum = 1;
	    foreach my $line (@$sheet) {
            my ($preartist,$artist)  = split(" - ",$line->[$offsets->{jumble}]);
            my ($units,$title)     = split(" x ",$preartist);
            my $price               = $line->[$offsets->{price}];
            my $fee                 = $line->[$offsets->{fee}];
            my $currency            = $line->[$offsets->{currency}];
            my $service_product_id  = $line->[$offsets->{service_product_id}];
            my ($product_type,$format,$free);
            my $mediaType = RPS::DB::Item::MediaType::kMediaTypeAudio;
            $free                   = 0;
            $units                  =~ s/\(orphaned transaction\) //;
            $product_type           = RPS::File::Sale::TYPE_ALBUM if($artist =~ /album/i);
            $product_type           = RPS::File::Sale::TYPE_TRACK if($artist !~ /album/i);
            $format                 = RPS::File::Sale::FORMAT_RINGTONE if($artist =~ /realtone/i);
            $format                 = RPS::File::Sale::FORMAT_DOWNLOAD if($artist =~ /music album/i || $artist =~ /music track/i);

            if($artist =~ /video download/i)
            {
                $format = RPS::File::Sale::FORMAT_DOWNLOAD; # was FORMAT_VIDEO (FB1324)
                $mediaType = RPS::DB::Item::MediaType::kMediaTypeVideo;
            }

            $price                  -= $fee;
            $price                  /= $units if($units!=0);
            $price                  *= -1 if($price < 0 && $units < 0);
            $free                    = 1 if($price eq "" || $price == 0);
            $artist                  =~ s/\(Music Track\)//;
            $artist                  =~ s/\(Music Title\)//;
            $artist                  =~ s/\(Mobile Realtone\)//;
            $artist                  =~ s/\(Music Album\)//;
            $artist                  =~ s/\(Video Download\)//;

			if ($units && $line->[$offsets->{jumble}] !~ /(Description|Podcast)/i && ($price || $free == 1) && $product_type ne "" && $line->[$offsets->{podcast_check}] !~ /podcast/i) {
                my $countryName = $line->[$offsets->{country}];
                $countryName = $line->[$offsets->{country}+1] if($countryName !~ /[a-zA-Z]/);
                my $country     = $Common::Consts::COUNTRY_CODE{lc $countryName};
                unless($country) {
                    print STDERR "Unknown country: " . $line->[$offsets->{country}]." line: ".$linenum."\n";
                    $self->errstr("Unknown country: ".$line->[$offsets->{country}]." line:".$linenum);
                    return undef;
                }

                my ($dateBegin,$dateEnd) = $self->_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 $sale = RPS::Import::SaleRec->new();

				$sale->productType($product_type);
				$sale->formatType($format);
				$sale->mediaType($mediaType);
				$sale->dateBegin($dateBegin);
				$sale->dateEnd($dateEnd);
                $sale->currencyCode($currency);
                $sale->countryCode($country);
                $sale->serviceProductID($service_product_id);
				$sale->artistName($artist);
				$sale->trackName($title);
				$sale->units(round($units));
				$sale->price(round($price,8));
                $sale->free($free);
				$sale->lineNum($linenum);
				$self->_insertSale(sale => $sale);
			}
            #else { print STDERR "skip s:".$sheet_names->[$sheet_count]." l:".$linenum." u: $units p: $price a: $artist t: $title\n"; }
            $linenum++;
		}
        $sheet_count++;
	}

	return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $self = shift;
    my $passed_date = shift;
    my ($month,$monthName,$year,$qtr,$dateBegin,$dateEnd);
    if($passed_date =~ m/(\d+)\D(\d+)\D(\d{4}) (\d+)\D(\d+)/) {
        $year = $3;
        $month = $2;
    }
    elsif($passed_date =~ m/(\d{4})\D(\d+)\D(\d+) (\d+)\D(\d+)/) {
        $year = $1;
        $month = $2;
    }
    elsif($passed_date =~ m/(\d+)\D(\d+)\D(\d+) /) {
        $year = 2000+$3;
        $month = $2;
    }
    if($month ne "" & $year ne "") {
        $dateBegin = sprintf("%04d-%02d-01", $year, $month);
        $dateEnd = sprintf("%04d-%02d-%02d", $year, $month,Days_in_Month($year,$month));
        return $self->SUPER::_getDates(date_begin => $dateBegin, date_end => $dateEnd);
    }
    else {
        return undef;
    }
}

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