package RPS::Import::Atlantic;

#Version 1 created from specs in Fog Bugz Case 9851

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 = (
    1 => {
        service      => 2,
        date_begin   => 3,
        date_end     => 4,
        artist       => 7,
        track        => 9,
        units        => 10,
        price        => 13,
        format       => 15,
        product_type => 16,
        isrc         => 17,
        upc          => 19,
        album        => 21,
        label        => 27,
    },
);

my %product_type_map = (
    "a" => RPS::File::Sale::TYPE_ALBUM,
    "p" => RPS::File::Sale::TYPE_TRACK,
    "s" => RPS::File::Sale::TYPE_ALBUM,
    "t" => RPS::File::Sale::TYPE_TRACK
);

my %format_map = (
    "emastertone"       => RPS::File::Sale::FORMAT_RINGTONE,
    "emd"               => RPS::File::Sale::FORMAT_DOWNLOAD,
    "eringback"         => RPS::File::Sale::FORMAT_RINGBACK,
    "esmstone"          => RPS::File::Sale::FORMAT_RINGTONE,    # was FORMAT_SMSTONE (FB1324)
    "usergenmastertone" => RPS::File::Sale::FORMAT_RINGTONE,    # was FORMAT_MASTERTONE (FB1324)
);

my %service_map = (
    "apple"                                => Client::Service::DSP_ITUNES,
    "amazon digital services inc"          => Client::Service::DSP_AMAZON,
    "9squared inc"                         => Client::Service::DSP_NINESQUARED,
    "mix and burn"                         => Client::Service::DSP_MIXANDBURN,
    "alltel communications"                => Client::Service::DSP_ALLTEL,
    "att mobility"                         => Client::Service::DSP_ATT,
    "t-mobile usa inc"                     => Client::Service::DSP_TMOBILE,
    "9squared - wmg storefronts"           => Client::Service::DSP_NINESQUARED,
    "sprint pcs"                           => Client::Service::DSP_SPRINT,
    "motricity inc - motricity storefront" => Client::Service::DSP_MOT_MOT,
);

my %service_error_hash;

#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  = ();

    $linenum = 1;

    my $currency_code = "USD";
    my $country_code  = "US";
    my $media_type    = RPS::DB::Item::MediaType::kMediaTypeAudio;

    foreach my $line (@$lines) {

        my $f_service      = $line->[ $offsets->{service} ];
        my $f_date_begin   = $line->[ $offsets->{date_begin} ];
        my $f_date_end     = $line->[ $offsets->{date_end} ];
        my $artist         = $line->[ $offsets->{artist} ];
        my $track          = $line->[ $offsets->{track} ];
        my $units          = $line->[ $offsets->{units} ];
        my $price          = $line->[ $offsets->{price} ];
        my $f_format       = lc $line->[ $offsets->{format} ];
        my $f_product_type = lc $line->[ $offsets->{product_type} ];
        my $f_isrc         = $line->[ $offsets->{isrc} ];
        my $upc            = $line->[ $offsets->{upc} ];
        my $album          = $line->[ $offsets->{album} ];
        my $label          = $line->[ $offsets->{label} ];

        my ( $date_begin, $date_end );

        $upc =~ s/[^0-9]//g;
        $f_isrc =~ s/[^0-9A-Z]//g;

        if (   ( $f_date_begin =~ /\d{4}\D\d{2}\D\d{2}/ )
            && ( $f_date_end =~ /\d{4}\D\d{2}\D\d{2}/ ) ) {

            ( $date_begin, $date_end ) = $self->_getDates(
                date_begin => $f_date_begin,
                date_end   => $f_date_end,
                type       => "iso"
            );
        }

        my $product_type;

        $product_type = $product_type_map{$f_product_type};

        my $format;

        $format = $format_map{$f_format};

        my $isrc;

        if ( $product_type eq RPS::File::Sale::TYPE_TRACK ) {
            $isrc = $f_isrc;
        }

        my $service_name = $f_service;

        $service_name =~ s/\(.*$//;
        my $service_id = $self->getServiceID($service_name) || $service_map{ lc $service_name };

        if (   $f_service
            && $f_date_begin
            && $f_date_end
            && $artist
            && ( $track || $album )
            && $units =~ /\d+/
            && $price =~ /\d+/
            && $f_format
            && $f_product_type
            && $f_isrc
            && $upc ) {
            if ( ( $units == 0 ) && ( $price == 0 ) ) {
                $linenum++;
                next;
            } elsif ( $price == 0 ) {
                $linenum++;
                next;
            }

            unless ( $date_begin && $date_end ) {
                $self->errstr( "Couldn't get dates from: " . "$f_date_begin, $f_date_end line number: $linenum" );

                print STDERR "Couldn't get dates from: " . "$f_date_begin, $f_date_end line number: $linenum\n";

                return undef;
            }

            unless ($product_type) {
                $self->errstr("Unknown product type: $f_product_type at linenum: $linenum");
                print STDERR "Unknown product type: $f_product_type at linenum: $linenum\n";
                return undef;
            }

            if ( !( defined $service_id ) && !$service_error_hash{$f_service} ) {
                $self->errstr( "Couldn't get service ID from $f_service " . "at line number $linenum" );

                print STDERR "couldn't get service ID from $f_service " . "at line number $linenum\n";

                $service_error_hash{$f_service} = 1;
            }

            my $sale = RPS::Import::SaleRec->new();
            $sale->serviceID($service_id);
            $sale->dateBegin($date_begin);
            $sale->dateEnd($date_end);
            $sale->artistName($artist);
            $sale->trackName($track) if ( $product_type eq RPS::File::Sale::TYPE_TRACK );
            $sale->formatType($format);
            $sale->productType($product_type);
            $sale->upc($upc);
            $sale->isrc($isrc) if ( $product_type eq RPS::File::Sale::TYPE_TRACK );
            $sale->albumName($album);
            $sale->labelName($label);

            $sale->currencyCode($currency_code);
            $sale->countryCode($country_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->price($price);

                #$args{dumper}($sale);  ## for cmd-line testing
                $self->_insertSale( sale => $sale );
            }
        }

        #else{print STDERR "SKIP line num: $linenum Service: $f_service date begin: $f_date_begin ".
        #"date end: $f_date_end artist: $artist track: $track album: $album ".
        #"units: $units price: $price format: $f_format product type: ".
        #"$f_product_type isrc: $f_isrc upc: $upc label: $label\n";}

        $linenum++;

    }

    return $linenum;
}

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