package RPS::Import::Uploader;

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 => {
        serviceName        => 0,
        date               => 3,
        labelName          => 5,
        artist             => 6,
        title              => 7,
        service_product_id => 8,
        upc                => 9,
        isrc               => 10,
        sale_format        => 11,
        countryName        => 12,
        delivery_format    => 13,
        units              => 14,
        currency           => 18,
        conversion         => 19,
        price              => 22,
    },
    2 => {
        serviceName        => 0,
        date               => 3,
        labelName          => 5,
        artist             => 6,
        title              => 7,
        isrc               => 8,
        service_product_id => 9,
        upc                => 10,
        sale_format        => 11,
        countryName        => 12,
        delivery_format    => 13,
        units              => 14,
        currency           => 18,
        conversion         => 19,
        price              => 22,
    },
);

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;
    return undef unless ( defined $args{sheets} && defined $version );

    my $sheet_names = $args{sheet_names};
    my ( $dateBegin, $dateEnd, $linenum, $currency );

    foreach my $sheet ( @{ $args{sheets} } ) {
        $linenum = 1;

        foreach my $line (@$sheet) {
            my $serviceName        = $line->[ $offsets->{serviceName} ];
            my $upc                = $line->[ $offsets->{upc} ];
            my $isrc               = $line->[ $offsets->{isrc} ];
            my $artist             = $line->[ $offsets->{artist} ];
            my $title              = $line->[ $offsets->{title} ];
            my $units              = round( $line->[ $offsets->{units} ] );
            my $price              = round( $line->[ $offsets->{price} ], 8 );
            my $countryName        = $line->[ $offsets->{countryName} ];
            my $currency           = $line->[ $offsets->{currency} ];
            my $labelName          = $line->[ $offsets->{labelName} ];
            my $conversion         = $line->[ $offsets->{conversion} ];
            my $service_product_id = $line->[ $offsets->{service_product_id} ];
            my $product_type;
            my $format;
            $product_type = RPS::File::Sale::TYPE_TRACK        if ( $line->[ $offsets->{sale_format} ] =~ /track/i );
            $product_type = RPS::File::Sale::TYPE_ALBUM        if ( $line->[ $offsets->{sale_format} ] =~ /bundle/i );
            $product_type = RPS::File::Sale::TYPE_ALBUM        if ( $line->[ $offsets->{sale_format} ] =~ /album/i );
            $product_type = RPS::File::Sale::TYPE_TRACK        if ( $line->[ $offsets->{sale_format} ] eq "" );
            $product_type = RPS::File::Sale::TYPE_TRACK        if ( $line->[ $offsets->{sale_format} ] =~ /(\d{8})/ );
            $upc          = $line->[ $offsets->{sale_format} ] if ( $line->[ $offsets->{sale_format} ] =~ /(\d{8})/ );
            $format       = RPS::File::Sale::FORMAT_DOWNLOAD   if ( $line->[ $offsets->{delivery_format} ] =~ /download/i );
            $format       = RPS::File::Sale::FORMAT_STREAM     if ( $line->[ $offsets->{delivery_format} ] =~ /stream/i );
            $format       = RPS::File::Sale::FORMAT_RINGTONE   if ( $line->[ $offsets->{delivery_format} ] =~ /tone/i );
            $format       = RPS::File::Sale::FORMAT_STREAM     if ( $line->[ $offsets->{delivery_format} ] =~ /play/i );
            $format       = RPS::File::Sale::FORMAT_DOWNLOAD   if ( $line->[ $offsets->{delivery_format} ] =~ /burn/i );
            $format       = RPS::File::Sale::FORMAT_DOWNLOAD   if ( $line->[ $offsets->{delivery_format} ] eq "" );
            $serviceName =~ s/vidzone/vidzonedigital/i;
            my $service = $self->getServiceID($serviceName);
            my $country = $Common::Consts::COUNTRY_CODE{ lc $countryName };
            $country = $countryName if ( $country eq "" && length($countryName) == 2 );
            $country = "GB"         if ( $country eq "" && $countryName eq "" );

            if ( $units && $artist ne "Artist" && $title ne "Title" ) {
                $price *= -1 if ( $units < 0 && $price < 0 );
                $price /= $units if ( $units > 1 );
                $price /= ( $units * -1 ) if ( $units < 0 );

                ( $dateBegin, $dateEnd ) = _getDates( $line->[ $offsets->{date} ] );
                print STDERR "Unknown format: " . $line->[ $offsets->{delivery_format} ] . " l:" . $linenum . "\n" if ( $format eq "" );
                print STDERR "Unknown type: " . $line->[ $offsets->{sale_format} ] . " l:" . $linenum . "\n" if ( $product_type eq "" );

                unless ( $dateBegin && $dateEnd ) {
                    $self->errstr( "Couldn't get dates from: " . $line->[ $offsets->{date} ] );
                    print STDERR "Couldn't get dates from: " . $line->[ $offsets->{date} ] . " l" . $linenum . "\n";
                    return undef;
                }
                unless ($country) {
                    $self->errstr( "Couldn't find country: " . $countryName );
                    print STDERR "Couldn't find country: " . $countryName . " l:" . $linenum . "\n";
                    return undef;
                }
                unless ($service) {
                    $self->errstr( "Couldn't find service: " . $serviceName );
                    print STDERR "Couldn't find service: " . $serviceName . " l:" . $linenum . "\n";
                    return undef;
                }

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

                $sale->formatType($format);
                $sale->productType($product_type);
                $sale->isrc($isrc) if ( $isrc ne "" );
                $sale->upc($upc)   if ( $upc ne "" );
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->labelName($labelName);
                $sale->serviceProductID($service_product_id);
                $sale->serviceID($service);
                $sale->currencyCode("GBP");
                $sale->countryCode($country);
                $sale->artistName($artist) if ( $artist ne "" );
                $sale->trackName($title)   if ( $product_type eq RPS::File::Sale::TYPE_TRACK );
                $sale->albumName($title)   if ( $product_type eq RPS::File::Sale::TYPE_ALBUM );
                $sale->units($units);
                $sale->price($price);
                $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 $passed_date = shift;
    my ( $month, $year, $dateBegin, $dateEnd );
    if ( $passed_date =~ m/(\d{4})\D(\d+)/ ) {
        $year  = $1;
        $month = $2;
    }
    if ( $month ne "" & $year ne "" ) {
        $dateBegin = $year . "-" . $month . "-01";
        $dateEnd = $year . "-" . $month . "-" . sprintf( "%02d", Days_in_Month( $year, $month ) );
        return ( $dateBegin, $dateEnd );
    } else {
        return undef;
    }
}

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