package RPS::Import::Musiwave3;

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);

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 = (
    13 => {
        country_col    => 0,
        price_col      => 6,
        date_col       => 1,
        begin_date_row => 5,
        end_date_row   => 6,
        psvcid         => 2,
        isrc           => 3,
        track          => 5,
        artist         => 6,
        label          => 7,
        units          => 8,
    },
);

#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} };

    my $unitPrice;

    return undef unless ($lines);

    my $gross_total = 0;

    my $linenum  = 1;
    my $sheetnum = 0;

    my $offsets = $field_map{$version};
    my %errors  = ();

    #$canadian_dollar = 1 if($fileName =~ /^CAD_/);

    my ( $dateBegin,   $dateEnd );
    my ( $countryCode, $unitPrice ) = getCountryPrice( $sheets[0] );
    my ( $dateBegin,   $dateEnd ) = extractDates( $sheets[1] );

    unless ( $countryCode && $unitPrice ) {
        $self->errstr("couldn't get country code and unit price from first sheet");
        return undef;
    }

    unless ( $dateBegin && $dateEnd ) {
        $self->errstr("couldn't get dates from sheet 2");

        return undef;
    }

    #print STDERR "Date begin: $dateBegin Date end: $dateEnd\n";

    my $type   = RPS::File::Sale::TYPE_TRACK;
    my $format = RPS::File::Sale::FORMAT_RINGTONE;

    foreach my $sheet (@sheets) {
        $sheetnum++;
        $linenum = 5;

        foreach my $line (@$sheet) {
            print STDERR "sheetnum: $sheetnum linenum: $linenum\n";
            my $service_product_id = $line->[ $offsets->{psvcid} ];
            my $artist             = $line->[ $offsets->{artist} ];
            my $track              = $line->[ $offsets->{track} ];
            my $isrc               = normalize_isrc( $line->[ $offsets->{isrc} ] );
            my $units              = $line->[ $offsets->{units} ];
            my $label              = $line->[ $offsets->{label} ];

            if (   $service_product_id =~ /\d+/
                && $artist
                && $track
                && $units
                && $label ) {

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

                $sale->serviceProductID($service_product_id);
                $sale->productType($type);
                $sale->formatType($format);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->isrc($isrc) if ($isrc);
                $sale->artistName($artist);
                $sale->trackName($track);
                $sale->units($units);
                $sale->price($unitPrice);
                $sale->labelName($label);
                $sale->currencyCode('EUR');
                $sale->countryCode($countryCode);
                $sale->lineNum($linenum);

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

            $linenum++;
        }
    }

    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $self       = shift;
    my $date_begin = shift;
    my $date_end   = shift;

    $date_begin =~ /(\d+)\/(\d+)\/(\d+)/;

    my $year = $3;

    if ( $year < 2000 ) {
        $year += 2000;
    }

    my ( $begin_month, $begin_day, $begin_year ) = ( $1, $2, $year );

    #print STDERR "Passed date begin: $date_begin date end: $date_end\n";

    $date_end =~ /(\d+)\/(\d+)\/(\d+)/;

    $year = $3;

    if ( $year < 2000 ) {
        $year += 2000;
    }

    my ( $end_month, $end_day, $end_year ) = ( $1, $2, $year );

    #print STDERR "End month $end_month end day $end_day ".
    "end year $end_year begin month $begin_month begin day $begin_day begin year $begin_year\n";

    if ( !( $end_month && $end_day && $end_year && $begin_month && $begin_day && $begin_year ) ) {
        return undef;
    }

    my $dateBegin = sprintf( "%04d-%02d-%02d", $begin_year, $begin_month, $begin_day );
    my $dateEnd   = sprintf( "%04d-%02d-%02d", $end_year,   $end_month,   $end_day );

    return ( $dateBegin, $dateEnd );

}

sub getCountryPrice {
    my $sheet = shift;

    my $country_col;
    my $unit_price_col;
    my $next_row = 0;

    my $country;
    my $unitPrice;

    foreach my $line (@$sheet) {
        my @line_array = @$line;
        my $array_size = @line_array;

        if ( $next_row == 1 ) {
            $country   = $line->[$country_col];
            $unitPrice = $line->[$unit_price_col];

            my $country_code = $COUNTRY_CODE{ lc $country };

            #print STDERR "Returning country $country_code, unit price: $unitPrice\n";

            return ( $country_code, $unitPrice );

        }

        foreach my $index ( 0 .. ( $array_size - 1 ) ) {
            my $cell = $line_array[$index];

            if ( $cell =~ /^country$/i ) {
                $country_col = $index;
                $next_row    = 1;
            }

            if ( $cell =~ /royalty per unit/i ) {
                $unit_price_col = $index;
                $next_row       = 1;
            }

        }
    }
}

sub extractDates {
    my $sheet = shift;

    my $date_begin;
    my $date_end;

    foreach my $line (@$sheet) {
        my @line_array = @$line;

        if ( $line_array[0] =~ /from:/i ) {
            $date_begin = $line_array[1];
        }

        if ( $line_array[0] =~ /to:/i ) {
            $date_end = $line_array[1];
        }
    }

    #print STDERR "Returning date_begin: $date_begin date_end: $date_end\n";

    return ( $date_begin, $date_end );
}

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