package RPS::Import::RSDigitalFmt2;

#Created from specs in Fog Bugz Case 9654

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

use lib '/app/tools/common/lib';
#use Common::Util;
use Common::Util qw(normalize_date normalize_isrc);
use Common::Consts qw(%COUNTRY_CODE %CODE_TO_COUNTRY);

use lib '/app/tools/data_classes/lib';
use Client::Service;

use lib '/app/tools/rps/lib';
use RPS::File::Sale;
use RPS::Import::Importer;
use base 'RPS::Import::Importer';

my %field_map = (
    2 =>
    {
        label              => 0,
        service_id         => 1,
        country            => 3,
        date_begin         => 4,
        date_end           => 5,
        product_type       => 6,
        format             => 7,
        service_product_id => 9,
        client_product_id  => 10,
        artist             => 11,
        upc                => 13,
        album              => 14,
        isrc               => 15,
        track_number       => 16,
        track              => 17,
        units              => 18,
        currency_code      => 19,
        free               => 22,
        price              => 24,
        media_type         => 25,
           
    },
);

my %product_type_map = ("a" => RPS::File::Sale::TYPE_ALBUM,
                        "t" => RPS::File::Sale::TYPE_TRACK);
                        
my %format_map       = ("1"  => RPS::File::Sale::FORMAT_DOWNLOAD,
                        "2"  => RPS::File::Sale::FORMAT_DOWNLOADPREMIUM,
                        "3"  => RPS::File::Sale::FORMAT_DOWNLOADUPGRADE,
                        "4"  => RPS::File::Sale::FORMAT_DUALDOWNLOAD,
                        "5"  => RPS::File::Sale::FORMAT_TETHERED,
                        "6"  => RPS::File::Sale::FORMAT_VPD,
                        "7"  => RPS::File::Sale::FORMAT_RINGTONE,
                        "8"  => RPS::File::Sale::FORMAT_RINGBACK,
                        "9"  => RPS::File::Sale::FORMAT_RINGTONE, # was FORMAT_SMSTONE (FB1324)
                        "10" => RPS::File::Sale::FORMAT_STREAM,
                        "11" => RPS::File::Sale::FORMAT_STREAM, # was FORMAT_VIDEOSTREAM (FB1324)
                        "12" => RPS::File::Sale::FORMAT_BACKGROUNDMUSIC,
                        "13" => RPS::File::Sale::FORMAT_JUKEBOX);
                        
my %media_type_map    = ("a" => RPS::DB::Item::MediaType::kMediaTypeAudio,
                         "v" => RPS::DB::Item::MediaType::kMediaTypeVideo);
                         
my %free_map          = ('y' => 1,
                         'n' => 0);


#public methods

sub _importLines
{
    my $self = shift;
    my %args = @_;

    my $lines = $args{lines};
    my $version = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    my @sheets = @{ $args{sheets} };

    return undef unless ($lines);

    my $linenum = 1;
            
    my $offsets = $field_map{$version};
    my %errors = ();
       
    my $currencyCode;   
    
    $linenum = 1;
    
    my @valid_services = Client::Service::GetAllServiceIDs();
    
    my %valid_services_hash;
    
    foreach my $service_id(@valid_services){
        $valid_services_hash{$service_id} = 1;
    }
        
    foreach my $line(@$lines)
    {
        my $label              = $line->[$offsets->{label}];
        my $service_id         = $line->[$offsets->{service_id}];
        my $country            = uc $line->[$offsets->{country}];
        my $f_date_begin       = $line->[$offsets->{date_begin}];
        my $f_date_end         = $line->[$offsets->{date_end}];
        my $f_product_type     = lc $line->[$offsets->{product_type}];
        my $f_format           = lc $line->[$offsets->{format}];
        my $service_product_id = $line->[$offsets->{service_product_id}];
        my $client_product_id  = $line->[$offsets->{client_product_id}];
        my $artist             = $line->[$offsets->{artist}];
        my $upc                = $line->[$offsets->{upc}];
        my $album              = $line->[$offsets->{album}];
        my $isrc               = $line->[$offsets->{isrc}];
        my $track_number       = $line->[$offsets->{track_number}];
        my $track              = $line->[$offsets->{track}];
        my $units              = $line->[$offsets->{units}];
        my $currency_code      = $line->[$offsets->{currency_code}];
        my $f_free             = lc $line->[$offsets->{free}];
        my $price              = $line->[$offsets->{price}];
        my $f_media_type       = lc $line->[$offsets->{media_type}];
                          
        $upc =~ s/[^0-9]//g;                      
        $isrc = normalize_isrc($isrc);
        
        my ($date_begin, $date_end) = $self->_getDates(date_begin => $f_date_begin, date_end => $f_date_end, type => 'iso');
        
        
#        if(($f_date_begin =~ /^\d{4}-\d{2}$/) && 
#        ($f_date_end =~ /^\d{4}-\d{2}$/)){
#            $f_date_begin = $f_date_begin."-01";
#            $f_date_end   = $f_date_end."-01";
#            
#            ($date_begin, $date_end) = 
#            $self->_getDates(date_begin=>$f_date_begin, 
#            date_end=>$f_date_end, type=>"iso");
#        }
#        else{
#            ($date_begin, $date_end) = (undef, undef);
#        }
        
        my $product_type = $product_type_map{$f_product_type};
        my $format       = $format_map{$f_format};
        my $free         = $free_map{$f_free};
        my $media_type   = $media_type_map{$f_media_type};                
        
        if($label && $service_id && $country && $f_date_begin && 
        $f_date_end && $f_product_type && $f_format && $artist &&
        ($upc || $album || $isrc || $track) && $units =~ /\d+/ &&
        $currency_code && $f_media_type) 
        {
            if(($units == 0) && ($price == 0)){
                $linenum++;
                next;                    
            }
            
            if(($units == 0) && ($free)){
                $self->errstr("Sale with no units has 'free' flag set at line number: $linenum");
                print STDERR "Sale with no units has 'free' flag set at line number: $linenum\n";
                return undef;
            }
            
            if(($units < 0) && ($free)){
                $self->errstr("Sale with negative units has 'free' flag set at line number: $linenum");
                print STDERR "Sale with negative units has 'free' flag set at line number: $linenum\n";
                return undef;
            }
            
            if((defined $price) && ($price != 0) && ($free)){
                $self->errstr("Price set for 'free' sale at line number: $linenum");
                print STDERR "Price set for 'free' sale at line number: $linenum\n";
                return undef;
            }           
            
            unless ($date_begin && $date_end) {
                $self->errstr("Couldn't get dates from $f_date_begin,". 
                "$f_date_end (need yyyy-mm), line number: $linenum");
                
                print STDERR "couldn't get dates from $f_date_begin,". 
                "$f_date_end (need yyyy-mm), line number: $linenum\n";
                return undef;
            }
            
            unless(($valid_services_hash{$service_id}) && ($service_id != 191)){
                $self->errstr("Invalid service ID $service_id at linenum: $linenum");                
                print STDERR "Invalid service ID $service_id at linenum: $linenum\n";
                return undef;
            }
            
            unless($product_type){
                $self->errstr("Invalid product type: $f_product_type (need 'A' or 'T') ".
                "at linenum: $linenum");                
                print STDERR "Invalid product type: $f_product_type (need 'A' or 'T') ".
                " at linenum: $linenum\n";
                return undef;
            }
                
            unless($format){
                $self->errstr("Invalid format ID: $f_format at line number: $linenum");
                print STDERR "Invalid format ID: $f_format at line number: $linenum\n";
                return undef;
            }
            
            unless($Common::Consts::CODE_TO_COUNTRY{$country}){
                $self->errstr("Invalid country code: $country at line number: $linenum");
                
                print STDERR "Invalid country code: $country at line number: $linenum\n";
                return undef;
            }
            
            unless($media_type){
                $self->errstr("Invalid media type: $f_media_type ".
                "(need 'A' or 'V') at line number: $linenum");
                
                print STDERR "Invalid media type: $f_media_type ".
                "(need 'A' or 'V') at line number: $linenum\n";
                return undef;
            }
            
            if(($media_type ne RPS::DB::Item::MediaType::kMediaTypeVideo) &&
               ($f_format eq '11')){
                $self->errstr("Media type set to 'Audio' for 'Video Stream' ".
                "format type at line number: $linenum");
                
                print STDERR "Media type set to 'Audio' for 'Video Stream' ".
                "format type at line number: $linenum\n";
                return undef;
            }
            
            
            if($f_free){
                if(!defined $free){
                    $self->errstr("Invalid free flag $f_free (need 'Y' or 'N' or empty) ".
                    " at line number: $linenum");
                    print STDERR "Invalid free flag $f_free (need 'Y' or 'N' or empty) ".
                    "at line number: $linenum\n";
                    return undef;
                }
            }
            
            my $sale = RPS::Import::SaleRec->new();
            $sale->labelName($label);
            $sale->serviceID($service_id);
            $sale->countryCode($country);
            $sale->dateBegin($date_begin);
            $sale->dateEnd($date_end);
            $sale->productType($product_type);
            $sale->formatType($format);
            $sale->serviceProductID($service_product_id);
            $sale->clientProductID($client_product_id);
            $sale->artistName($artist);
            $sale->upc($upc);
            $sale->albumName($album);
            $sale->isrc($isrc) if($product_type eq RPS::File::Sale::TYPE_TRACK);
            $sale->trackNum($track_number) if($product_type eq RPS::File::Sale::TYPE_TRACK);
            $sale->trackName($track) if($product_type eq RPS::File::Sale::TYPE_TRACK);
            $sale->currencyCode($currency_code);
            $sale->mediaType($media_type);                     
            $sale->lineNum($linenum);
            
            if(($units == 0) && ($price != 0)){          
                
                if($price < 0){                    
                    $sale->units(-1);                    
                    $sale->price(abs $price);                                
                    $self->_insertSale(sale => $sale);
                    
                    $sale->units(1);
                    $sale->price(0);
                    $self->_insertSale(sale => $sale);
                }
                elsif($price > 0){
                    $sale->units(1);
                    $sale->price($price);
                    $self->_insertSale(sale => $sale);
                    
                    $sale->units(-1);
                    $sale->price(0);
                    $self->_insertSale(sale => $sale);
                }
            }
            else{
                          
                if(($units > 0) && ($price > 0)){
                    $price /= $units;
                }
                elsif(($units > 0) && ($price < 0)){            
                    $price = (abs $price)/$units;
                    $units *= -1;
                }
                elsif(($units < 0) && ($price > 0)){
                    $price = $price / (abs $units);
                }
                elsif(($units < 0) && ($price < 0)){
                    $price = (abs $price) / (abs $units);
                }               
                
                $sale->units($units);
                $sale->free($free) if($free);
                $sale->price($price) if(!$free);              
            
                #$args{dumper}($sale);  ## for cmd-line testing
                $self->_insertSale(sale => $sale);
            }
        }
        
        $linenum++;
        
    }
    

    return $linenum;
}

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