package RPS::Import::Welk;

use strict;

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

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

# map version num to the field order
my %fieldMap = (
    1 => {
        country          => 1,
        date             => 2,
        catalog          => 4,
        album_and_artist => 5,
        format           => 6,
        upc              => 7,
        channel          => 8,
        level            => 9,
        units            => 10,
        price            => 11,
        runits           => 12,
        rprice           => 13,
    },
    2 => {
        country          => 1,
        date             => 2,
        catalog          => 7,
        album_and_artist => 8,
        format           => 9,
        upc              => 10,
        channel          => 11,
        level            => 12,
        units            => 13,
        price            => 14,
        runits           => 15,
        rprice           => 16,
    },
);

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 $lines    = $args{lines};
    my $fileObj  = $args{file};
    my $version  = $args{file}->VersionNum();
    my $fileName = $fileObj->OrigFileName;

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

    my $offsets = $fieldMap{$version};

    my $linenum = 1;
    foreach my $line (@$lines) {
        my ( $artist, $album ) = split( "/", $line->[ $offsets->{album_and_artist} ] );
        my $service_product_id = $line->[ $offsets->{catalog} ];
        my $product_type       = $line->[ $offsets->{format} ];
        my $raw_type           = $product_type;
        my $channel            = $line->[ $offsets->{channel} ];
        my $level              = lc $line->[ $offsets->{level} ];
        my $print_bool         = 0;

        my $upc     = $line->[ $offsets->{upc} ];
        my $units   = $line->[ $offsets->{units} ];
        my $price   = $line->[ $offsets->{price} ];
        my $returns = $line->[ $offsets->{runits} ];
        my $rprice  = $line->[ $offsets->{rprice} ];
        $rprice *= -1 if ( $rprice < 0 );
        my $currency = "USD";
        my $country  = $line->[ $offsets->{country} ];

        #my ($month, $day, $year)
        #print STDERR "Date begin: ".sprintf("%02d/%02d/%04d",split("/",$line->[$offsets->{date}]));

        my ( $dateBegin, $dateEnd );

        if ( $line->[ $offsets->{date} ] =~ /\d{4}\D\d{2}\D\d{2}/ ) {

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

        my $total = $price - $rprice;

        $returns *= -1 if ( $returns < 0 );

        #$price /= $units if($units>1);
        #$rprice /= $returns if($returns>1);

        $product_type = RPS::File::Sale::TYPE_LP     if ( $product_type eq "LP" );
        $product_type = RPS::File::Sale::TYPE_CD     if ( $product_type eq "CD" );
        $product_type = RPS::File::Sale::TYPE_DBL_CD if ( $product_type eq "CD2" );
        $product_type = RPS::File::Sale::TYPE_VHS    if ( $product_type eq "VHS" );
        $product_type = RPS::File::Sale::TYPE_DVD    if ( $product_type eq "DVD" );
        $product_type = RPS::File::Sale::TYPE_CASS   if ( $product_type eq "CASS" );
        if ( $channel =~ /retail/i || $channel =~ /artist/i ) {
            $channel = RPS::File::Sale::CHANNEL_RETAIL;
        } elsif ( $channel =~ /direct|mechanical/i ) {    # for now, treat mechanical as direct
            $channel = RPS::File::Sale::CHANNEL_DIRECT;
        } elsif ( $channel =~ /mail order/i ) {
            $channel = RPS::File::Sale::CHANNEL_MAILORDER;
        }

        $level =
            $level =~ /full/    ? RPS::File::Sale::PLEVEL_FULL
          : $level =~ /midline/ ? RPS::File::Sale::PLEVEL_MID
          : $level =~ /budget/  ? RPS::File::Sale::PLEVEL_BUDGET
          : $level =~ /promo/   ? RPS::File::Sale::PLEVEL_PROMO
          :                       '';

        if ( ( $units > 0 || $returns > 0 ) && $product_type !~ /\*\*/ && $line->[ $offsets->{album_and_artist} ] !~ /album_name/ ) {

            unless ( $channel eq RPS::File::Sale::CHANNEL_RETAIL
                || $channel eq RPS::File::Sale::CHANNEL_DIRECT
                || $channel eq RPS::File::Sale::CHANNEL_MAILORDER ) {
                $self->errstr("Unknown Sales Channel: $channel l:$linenum");
                return undef;
            }

            unless ( $level eq RPS::File::Sale::PLEVEL_FULL
                || $level eq RPS::File::Sale::PLEVEL_MID
                || $level eq RPS::File::Sale::PLEVEL_BUDGET
                || $level eq RPS::File::Sale::PLEVEL_PROMO ) {
                $self->errstr("Unknown Price Level: $level l:$linenum");
                return undef;
            }

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

            my $sale = RPS::Import::SaleRec->new();
            $sale->configuration($raw_type);
            $sale->productType($product_type);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->clientProductID($service_product_id);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->upc($upc);
            $sale->priceLevel($level);
            $sale->sales($units);
            $sale->salesRevenue($price);
            $sale->returns($returns);
            $sale->returnsRevenue($rprice);
            $sale->channel($channel);
            $sale->salesRevenue($price);
            $sale->totalRevenue($total);
            $sale->countryCode($country);
            $sale->currencyCode($currency);
            $sale->lineNum($linenum);
            $self->_insertSale( sale => $sale );
        }

        #else { print STDERR "Skip-> l:".$linenum." u:".$units." p:".$price." ar: ".$artist." al:".$album."<-Skip\n";}
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

#sub _getDates
#{
#	my $date = shift;

#	my $beginDate;
#	my $endDate;
#    if ($date =~ m/(\d{4})\D(\d+)\D(\d+)/) {
#        my $year = $1;
#        my $month = $2;
#        $beginDate = $year."-".$month."-01";
#        $endDate = $year."-".$month."-".Days_in_Month($year, $month);
#	    return ($beginDate, $endDate);
#    }
#    return undef;
#}

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