package RPS::Import::SDROutsideSales;

use strict;

use lib '/app/tools/common/lib';
use Common::Country;
use Date::Calc qw(Days_in_Month Decode_Month Add_Delta_Days);

use lib '/app/tools/data_classes/lib';

# map version num to the field order
my %fieldMap = (
    1 => {
        country            => 3,
        date               => 5,
        scountry           => 8,
        label              => 9,
        service_product_id => 11,
        album              => 12,
        units              => 13,
        price              => 14,
    },
    2 => {
        country            => 3,
        date               => 5,
        scountry           => 8,
        label              => 10,
        service_product_id => 11,
        album              => 12,
        units              => 13,
        price              => 14,
    },
    3 => {
        date               => 5,
        label              => 10,
        country            => 11,
        service_product_id => 12,
        album              => 13,
        units              => 14,
        price              => 15,
    },
    4 => {
        date               => 4,
        label              => 9,
        country            => 10,
        service_product_id => 11,
        album              => 12,
        units              => 13,
        price              => 14,
    },
);

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

#public methods

my %product_type_map = (
    1 => RPS::File::Sale::TYPE_LP,
    2 => RPS::File::Sale::TYPE_CD
);

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

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

    return undef unless ( defined $sheets && defined $version );

    my $offsets = $fieldMap{$version};
    my ( $linenum, $country, $countryCode );
    my %errors = ();

    foreach my $sheet ( @{ $args{sheets} } ) {
        $linenum = 1;
        foreach my $line (@$sheet) {
            my $f_album_artist       = $line->[ $offsets->{album} ];
            my $f_service_product_id = $line->[ $offsets->{service_product_id} ];
            my $units                = $self->numeric( $line->[ $offsets->{units} ] );
            my $price                = $self->numeric( $line->[ $offsets->{price} ] );

            if ( $line->[ $offsets->{country} ] ne '' ) {
                $country = lc $line->[ $offsets->{country} ];
                next if ( $country =~ /total\s+/ );

                $countryCode =
                    $country =~ /europe/    ? 'EU'
                  : $country =~ /australia/ ? 'AU'
                  : $country =~ /japan/     ? 'JP'
                  : $country =~ /america/   ? 'US'
                  : $country =~ /kingdom/   ? 'GB'
                  : $country =~ /greese/    ? 'GR'
                  :                           uc $country;
            }

            my $f_product_type;
            my $upc;
            my $service_product_id;

            if ( $version == 3 ) {
                ( $upc, $f_product_type ) = split( "-", $f_service_product_id );
            } else {
                ( $service_product_id, $f_product_type ) = split( "-", $f_service_product_id );
            }

            my $product_type = $product_type_map{$f_product_type};

            my $album;
            my $artist;

            my @album_artist = split( ": ", $f_album_artist );

            if ( @album_artist == 1 ) {

                ($album) = @album_artist;
            } else {
                ( $artist, $album ) = @album_artist;
            }

            #my $product_type =
            #    $service_product_id =~ /\-2/ ? RPS::File::Sale::TYPE_CD :
            #    $service_product_id =~ /\-1/ ? RPS::File::Sale::TYPE_LP :
            #    '';

            #next unless ($album && $price && $units && $product_type);
            unless ( ( $album || $artist ) && $price && $units && ( $upc || $service_product_id ) ) {
                print STDERR "Skip-> l:$linenum u:$units p:$price c:$country al:$album t:$product_type\n";
                next;
            }

            if ($countryCode) {
                my $obj = Common::Country->Get($countryCode);
                if ( !$obj ) {
                    $self->errstr("Unknown country '$countryCode' in line number: $linenum");
                    return undef;
                } else {
                    $countryCode = $obj->alpha2();
                }
            }

            # if we still dont have a country code, theres a problem
            unless ($countryCode) {
                my $c = $country;
                unless ( defined $errors{$c} ) {
                    $self->errstr("invalid country: $country at row number: $linenum");
                    print STDERR "no country at $linenum\n";
                    $errors{$c} = 1;
                }

                # let it continue to import just so we can report ALL bad countries
            }

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

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

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

            my $sale = RPS::Import::SaleRec->new();
            $sale->productType($product_type);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->clientProductID($service_product_id) if ($service_product_id);
            $sale->upc($upc)                            if ($upc);
            $sale->albumName($album);
            $sale->artistName($artist) if ($artist);
            $sale->totalRevenue( $units * $price );
            $sale->wholesalePrice($price);

            if ( $units > 0 )    # sales
            {
                $sale->sales($units);
                $sale->salesRevenue( $price * $units );
            } else               # returns
            {
                $units *= -1 if ( $units < 0 );
                $sale->returnsRevenue( $price * $units );
                $sale->returns($units);
            }

            $sale->countryCode($countryCode);
            $sale->channel(RPS::File::Sale::CHANNEL_RETAIL);
            $sale->priceLevel(RPS::File::Sale::PLEVEL_FULL);
            $sale->lineNum($linenum);
            $self->_insertSale( sale => $sale );
        } continue {
            $linenum++;
        }
    }
    return $linenum;
}

#
# Private methods
#

#sub _getDates
#{
#    my $date = shift;
#    my ($beginDate,$endDate,$year,$month,$day);

#    if($date =~ m/(\d{5})/) {
#        ($year, $month, $day) = Add_Delta_Days(1900,1,1, $1 - 2);
#    }
#    elsif ($date =~ m/(\d{4})\D(\d+)\D(\d+)/) {
#        $year = $1;
#        $month = $2;
#    }
#    elsif($date =~ m/(\d+)\D(\d+)\D(\d{4})/) {
#        $year = $3;
#        $month = $1;
#    }

#    if($year ne "" & $month ne "") {
#        $beginDate = $year."-".$month."-01";
#        $endDate = $year."-".$month."-".Days_in_Month($year, $month);
#        return ($beginDate,$endDate);
#    }
#    return undef;
#}

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