package RPS::Import::AOL2;

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 = (
    5 => {
        begin_date => 0,
        end_date   => 1,
        label      => 2,
        track      => 4,
        artist     => 5,
        upc        => 6,
        isrc       => 7,
        psvcid     => 9,
        country    => 10,
        units      => 11,
    },
);

#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 $gross_total = 0;

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

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

    my ( $dateBegin, $dateEnd );

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

    my $format;
    my $mediaType;

    if ( $self->is_wmg ) {
        $format    = RPS::File::Sale::FORMAT_STREAM;              # was FORMAT_VIDEOSTREAM (FB1324)
        $mediaType = RPS::DB::Item::MediaType::kMediaTypeVideo;
    } else {
        $format    = RPS::File::Sale::FORMAT_STREAM;
        $mediaType = RPS::DB::Item::MediaType::kMediaTypeAudio;
    }

    $linenum = 1;

    foreach my $line (@$lines) {
        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 $upc                = $line->[ $offsets->{upc} ];
        my $label              = $line->[ $offsets->{label} ];
        my $units              = $line->[ $offsets->{units} ];
        my $country            = $line->[ $offsets->{country} ];

        $track =~ s/^'(.*)'$/$1/;

        my $f_date_begin;
        my $f_date_end;

        $f_date_begin = $line->[ $offsets->{end_date} ];
        $f_date_end   = $line->[ $offsets->{begin_date} ];

        my ( $dateBegin, $dateEnd ) = ( $f_date_begin, $f_date_end );

        if ( $track && $artist && $label && $units && $country && ( $f_date_begin =~ /\d+/ ) ) {
            unless ( $dateBegin && $dateEnd ) {
                $self->errstr("couldn't get dates from $f_date_begin, $f_date_end at row $linenum ");
                print STDERR "$fileName\n";
                return undef;
            }

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

            $sale->serviceProductID($service_product_id);
            $sale->productType($type);
            $sale->formatType($format);
            $sale->mediaType($mediaType);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->isrc($isrc) if ( is_valid_isrc($isrc) );
            $sale->upc($upc)   if ( $upc =~ /\d+/ );
            $sale->labelName($label);
            $sale->artistName($artist);
            $sale->trackName($track);
            $sale->units($units);
            $sale->countryCode($country);
            $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;

    my $year_begin;
    my $month_begin;
    my $day_begin;

    my $year_end;
    my $month_end;
    my $day_end;

    print STDERR "Date begin: $date_begin\n";
    print STDERR "Date end passed in: $date_end\n";

    if ( $date_begin =~ /^(\d+)$/ ) {

        ( $year_begin, $month_begin, $day_begin ) = Add_Delta_Days( 1900, 1, 1, $1 - 2 );

    } else {
        return undef;
    }

    if ( $date_end =~ /^(\d+)$/ ) {

        ( $year_end, $month_end, $day_end ) = Add_Delta_Days( 1900, 1, 1, $1 - 2 );

    } else {
        return undef;
    }

    my $dateBegin = sprintf( "%04d-%02d-%02d", $year_begin, $month_begin, 1 );
    my $dateEnd = sprintf( "%04d-%02d-%02d", $year_end, $month_end, Days_in_Month( $year_end, $month_end ) );

    return ( $dateBegin, $dateEnd );

}

#------------------------------------------------------------
# bool is_valid_isrc
#
# Determine if a target string is a valid isrc code
#
# Scheme found at:
#
#  http://en.wikipedia.org/wiki/International_Standard_Recording_Code
#
# Parameters:
#   $target - scalar containing a string to test.
#
# Return:
#   bool - true if a valid list, otherwise undef
#------------------------------------------------------------
sub is_valid_isrc {
    my $isrc = shift || return 1;

    return undef unless ( defined($isrc) );

    $isrc =~ /^(..)(...)(..)(.*)/;
    my ( $country_code, $company, $year, $id ) = ( $1, $2, $3, $4, $5 );

    return undef unless ( defined($country_code)
        && defined($company)
        && defined($year)
        && defined($id) );

    $country_code = uc($country_code);
    return undef unless ( $country_code =~ /\D{2}/ );
    return undef unless ( $company =~ /^[\d\w]{3}$/ );
    return undef unless ( $year =~ /^\d{2}$/ );
    return undef unless ( $id =~ /^\d{5}$/ );

    return 1;
}

#------------------------------------------------------------
# bool is_valid_upc_or_ean
#
# Determine if a string represents a valid UPC-a or EAN13
# code with a valid check digit.
#
# Parameters:
#   $target - scalar containing a string to test.
#
# Return:
#   bool - true if a valid list, otherwise undef
#------------------------------------------------------------
sub is_valid_upc_or_ean {
    my $barcode = shift || return 1;

    return undef unless ( defined($barcode) );

    if ( length($barcode) == 12 ) {
        my $upc = new Business::UPC($barcode) || return undef;
        return $upc->is_valid();
    } elsif ( length($barcode) == 13 ) {
        return valid_barcode($barcode);
    } else {
        return undef;
    }

    return undef;
}

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