package RPS::Import::TuneTribeSMS;

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 = (
        3 => {
            artist      => 0,
            title       => 1,
            catalog     => 4,
            service     => 5,
            units       => 17,
            price       => 18,
            month1      => 7,
            month2      => 8,
            month3      => 9,
            month4      => 10,
        },
);

#public methods

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 $header_found = 0;
    my $linenum = 1;
    my ($dateBegin,$dateEnd,$dateYear,@months);
    $fileName   =~ m/(\d{4})/;
    $dateYear   = $1;

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

            foreach my $line (@$sheet) {
                my $country             = "GB";
                my $currency            = "GBP";
                my $product             = RPS::File::Sale::TYPE_TRACK;
                my $format              = RPS::File::Sale::FORMAT_RINGTONE; # was FORMAT_SMSTONE (FB1324)
                my $mediaType           = RPS::DB::Item::MediaType::kMediaTypeAudio;
                my $artist              = $line->[$offsets->{artist}];
                my $catalog             = $line->[$offsets->{catalog}];
                my $serviceName         = $line->[$offsets->{service}];
                my $title               = $line->[$offsets->{title}];
                my $units               = $line->[$offsets->{units}];
                my $price               = $line->[$offsets->{price}];

                if($linenum == 1 && $sheet_count == 0) {
                    $months[0]  = $line->[$offsets->{month1}];
                    $months[1]  = $line->[$offsets->{month2}];
                    $months[2]  = $line->[$offsets->{month3}];
                    $months[3]  = $line->[$offsets->{month4}];
                    $dateEnd    = $dateYear."-".sprintf("%02d",Decode_Month($months[3]))."-".Days_in_Month($dateYear,Decode_Month($months[3]));
                    $dateYear-- if(Decode_Month($months[3])<3 && Decode_Month($months[0])>10);
                    $dateBegin  = $dateYear."-".sprintf("%02d",Decode_Month($months[0]))."-01";
                }
                elsif ($units != 0 && $country && $price && $title && $title ne "Title") {

                    my $service_id      = $self->getServiceID(lc ($serviceName));

                    unless (defined $dateBegin && defined $dateEnd) {
                        print STDERR "Couldn't get dates from: ". $sheet->[$offsets->{date_start_row}]->[$offsets->{date_col}] . "\n";
                        $self->errstr("couldn't get dates from: ".$sheet->[$offsets->{date_end_row}]->[$offsets->{date_col}]);
                        return undef;
                     }

                     unless ($service_id) {
                        print STDERR "Unknown service: ". $line->[$offsets->{service}]." (".$linenum.")\n";
                        $self->errstr("Unknown service: ". $line->[$offsets->{service}]." (".$linenum.")");
                        return undef;
                     }

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

                     $sale->mediaType($mediaType);
                     $sale->productType($product);
                     $sale->dateBegin($dateBegin);
                     $sale->dateEnd($dateEnd);
                     $sale->serviceID($service_id);
                     $sale->serviceProductID($catalog);
                     $sale->artistName($artist);
                     $sale->trackName($title);
                     $sale->formatType($format);
                     $sale->units($units);
                     $sale->price($price);
                     $sale->countryCode($country);
                     $sale->currencyCode($currency);
                     $sale->lineNum($linenum+1);

                     $self->_insertSale(sale => $sale);
                } 
                #else { print STDERR "skip l: " . $linenum . " - c:".$country." p:".$price." c:".$catalog." t:".$title." f:".$format."\n"; }
                $linenum++;
            }
        }
        $sheet_count++;
    }
	return $linenum;
}

#
# Private methods
#


sub _getDates
{
    my ($year,$month,$day,$monthName,$qtr,$passed_date,$dateBegin,$dateEnd);
	$passed_date = shift;
    $passed_date =~ s/\s.*$//;
    #print STDERR "|>".$passed_date."<|\n";
    if($passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/) {
            $year   = $1;
            $month  = $2;
            $day    = $3;
    }
    elsif($passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/) {
        $year = $3;
        $month = $1;
        $day = $2;
    }
    if($year && $month && $day) {
        return ($year."-".sprintf("%02d",$month)."-".sprintf("%02d",$day));
    }

    return undef;
}

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