package RPS::Import::DigitalTunes;

use strict;

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

use lib '/app/tools/common/lib';
use Common::Country;

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            => 0,
            product         => 1,
            artist_track    => 2,
            label           => 3,
            upc             => 4,
            catalog         => 5,
            isrc            => 7,
            price           => 14,
            country         => 15,
        },
);

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

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

    # Flg1904, if set, means that the sales file originated in
    # Excel and that it's using a 1904 epoch.  See RPS/Sale/File.pm.
    #
    # Thus, if the date looks like an Excel encoding, we can properly
    # decode it using ExcelFmt.
    #
    my $is_1904 = (defined $args{Flg1904}) ? 1 : undef;

    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;

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

            foreach my $line (@$sheet) {
                my $countryName         = $line->[$offsets->{country}];
                my $currency            = "EUR";  # See FB13588
                my ($artist,$track)     = split(" : ",$line->[$offsets->{artist_track}]);
                my $format              = RPS::File::Sale::FORMAT_DOWNLOAD;
                my $product             = $product_map{lc($line->[$offsets->{product}])};
                my $units               = 1;
                my $price               = $line->[$offsets->{price}];
                my $label               = $line->[$offsets->{label}];
                my $isrc                = $line->[$offsets->{isrc}];
                my $upc                 = int($line->[$offsets->{upc}]);

                if ($units && $line->[$offsets->{artist_track}] ne "Item" && $price && $track) {

                    unless ( defined $countryName && '' ne $countryName )
                    {
                        $self->errstr("Missing country on line $linenum");
                        return undef;
                    }

                    my $countryObj = Common::Country->Get( $countryName );
                    my $countryCode = $countryObj->alpha2 if ( $countryObj );

                    unless ( defined $countryCode )
                    {
                        $self->errstr("Unrecognized country on line $linenum: $countryName");
                        return undef;
                    }

                    my ($dateBegin,$dateEnd)= $self->_getDates( $line->[$offsets->{date}], $is_1904 );

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

                    unless ($product ne "") {
                        print STDERR "Couldn't get product from: ". $line->[$offsets->{product}] . " l:".$linenum."\n";
                        $self->errstr("Couldn't get product from: ". $line->[$offsets->{product}] . " l:".$linenum);
                    }



                    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->trackName($track) if($product eq RPS::File::Sale::TYPE_TRACK);
                    $sale->albumName($track) if($product eq RPS::File::Sale::TYPE_ALBUM);
                    $sale->artistName($artist);
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->isrc($isrc) if($product eq RPS::File::Sale::TYPE_TRACK);
                    $sale->upc($upc);
                    $sale->countryCode($countryCode);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);

                    $self->_insertSale(sale => $sale);
                } 
                #else { print STDERR "skip sh: ".$sheet_names->[$sheet_count] . ": l: " . $linenum . " - u:".$units." p:".$price." a:".$artist." t:".$track." f:".$format."\n"; }
                $linenum++;
            }
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#


sub _getDates
{
    my $self = shift;
    my $passed_date = shift;
    my $is_1904 = shift;

    $passed_date =~ s/\s.*$//;

    my $year;
    my $month;

    if( $passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/)
    {
        $year = $1;
        $month = $2;
    }
    elsif($passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/)
    {
        $year = $3;
        $month = $1;
    }
    elsif( $passed_date =~ /(\d{5})\.(\d{11})/ || $passed_date =~ /(\d{5})/  )  # Excel encoding, with or without timestamp
    {
        my $prefix = $1;
        my $_date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $1, $is_1904 );

        ($year, $month) = split("-", $_date);

    }

    if($year && $month) {
        return ($year."-".$month."-01", $year."-".$month."-".Days_in_Month($year,$month));
    }
    return undef;
}

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