package RPS::Import::EMI::v1;

use strict;

use Date::Calc qw(Days_in_Month);

use lib '/app/tools/rps/lib';
use RPS::CountryList;

use lib '/app/tools/common/lib';
use Common::Consts qw(%COUNTRY_TO_CODE);
use Common::RSMath qw(round);

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

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

my %field_map = (
    1 => {
        label           => 0,
        productID       => 1,
        title           => 2,
        upc             => 3,
        sale_units      => 4,
        sales_revenue   => 5,
        return_units    => 6,
        returns_revenue => 7,
        net_units       => 8,
        total_revenue   => 9,
        formatType      => 10,
    },

);

#
# public methods
#

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

    return undef unless ($lines);
    my $version  = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();

    my $currencyCode;
    my $countryCode;

    # If the filename contains "_CA" or "_CANADA", followed by spaces or an underscore or period,
    # then assume it's Canadian.
    # If the filename contains "_US" or "_USA", followed by spaces or an underscore or period,
    # then assume it's US.
    #
    if ( $fileName =~ /_ca(nada)?(\s+|_|\.)/i ) {
        $currencyCode = "CAD";
        $countryCode  = "CA";
    } elsif ( $fileName =~ /_us(a)?(\s+|_|\.)/i ) {
        $currencyCode = "USD";
        $countryCode  = "US";
    } else {
        $self->errstr("Filename doesn't contain CA or US");
        return undef;
    }

    my $offsets = $field_map{$version};

    my ( $dateBegin, $dateEnd );

    my $month_selector = "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)";
    if ( lc($fileName) =~ /$month_selector.*[_ ](\d{4})/ ) {
        my $month = $1;
        my $year  = $2;
        ( $dateBegin, $dateEnd ) =
          $self->_getDates( date_begin => $self->_formatDate( 1, $month, $year ) );

    } elsif ( lc($fileName) =~ /$month_selector.*[_ ](\d{2})/ ) {
        my $month = $1;
        my $year  = $2 + 2000;
        ( $dateBegin, $dateEnd ) =
          $self->_getDates( date_begin => $self->_formatDate( 1, $month, $year ) );
    } else {
        ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $fileName, type => "numerical_year_first" );
    }

    unless ( $dateBegin && $dateEnd ) {
        $self->errstr("couldn't get dates");
        print STDERR "file name: $fileName\n";
        return undef;
    }

    my $linenum = 1;

    my $summaryFound;

    foreach my $line (@$lines) {

        my ( $artist, $title ) = split( "/", $line->[ $offsets->{title} ] );

        my ($price);
        my ($net_units)     = $line->[ $offsets->{net_units} ];
        my ($total_revenue) = $line->[ $offsets->{total_revenue} ];

        my $formatType = $line->[ $offsets->{formatType} ];
        my $productID  = $line->[ $offsets->{productID} ];
        my $label      = $line->[ $offsets->{label} ];

        my $mediaType =
          ( $productID =~ m/^EMIDV/ )
          ? RPS::DB::Item::MediaType::kMediaTypeVideo
          : RPS::DB::Item::MediaType::kMediaTypeAudio;

        if ( $formatType eq "D" ) {
            $formatType = RPS::File::Sale::FORMAT_DOWNLOAD;
        } elsif ( $formatType eq "S" ) {
            $formatType = RPS::File::Sale::FORMAT_STREAM;
        } elsif ( $formatType eq "M" ) {
            $formatType = RPS::File::Sale::FORMAT_RINGTONE;
        } else {
            $formatType = undef;
        }

        # Stop processing lines if we hit the summary section (FB1799)
        #
        if ( $summaryFound || $label =~ /^SUMMARIZED TOTALS BY TYPE$/i ) {
            $summaryFound = 1;
            next;
        }

        if (   $label
            && $productID
            && ( $net_units =~ m/-?\d+/ && $net_units != 0 && $total_revenue =~ m/-?\d*\.?\d*/ ) ) {
            my $albumName;
            my $trackName;
            my $upc;
            my $isrc;
            my $productType;

            my $_upc = $line->[ $offsets->{upc} ];
            if ( $_upc =~ m/^\d{12,13}$/ ) {
                $upc         = $_upc;
                $albumName   = $title;
                $productType = RPS::File::Sale::TYPE_ALBUM;
            } elsif ( length($_upc) == 12 && $_upc =~ m/^\D\D...\d{7}$/ ) {
                $isrc        = $_upc;
                $trackName   = $title;
                $productType = RPS::File::Sale::TYPE_TRACK;
            } else {
                print STDERR "Line $linenum: Unable to determine product type from upc/isrc '$_upc'\n";
                $self->errstr("Line $linenum: Unable to determine product type");
                return undef;
            }

            # Create a record for sales
            #
            my $sale = RPS::Import::SaleRec->new();

            $price = 0;
            if ( $net_units != 0 ) {
                $price = abs( $total_revenue / $net_units );
            }

            $net_units = abs($net_units);

            $net_units *= -1 if ( $total_revenue < 0 );

            $sale->trackName($trackName) if ($trackName);
            $sale->albumName($albumName) if ($albumName);
            $sale->productType($productType);
            $sale->mediaType($mediaType);

            $sale->formatType($formatType);
            $sale->serviceProductID($productID);
            $sale->labelName($label);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->artistName($artist);
            $sale->isrc($isrc) if ($isrc);
            $sale->upc($upc)   if ($upc);
            $sale->countryCode($countryCode);
            $sale->currencyCode($currencyCode);
            $sale->lineNum($linenum);

            $sale->units($net_units);
            $sale->price($price);

            $self->_insertSale( sale => $sale );
        }

        #else { print STDERR "Skipped: linenum: $linenum format type($formatType) netUnits($net_units) totalRevenue($total_revenue)\n"; }

        $linenum++;
    }

    return $linenum;
}

#
# Private methods
#
sub _formatDate {
    my $self   = shift;
    my $day    = shift;
    my $month  = lc(shift);
    my $year   = shift;
    my %months = (
        jan => 1,
        feb => 2,
        mar => 3,
        apr => 4,
        may => 5,
        jun => 6,
        jul => 7,
        aug => 8,
        sep => 9,
        oct => 10,
        nov => 11,
        dec => 12
    );

    my $date = sprintf( "%04s-%02s-%02s", $year, $months{$month}, $day );
    return $date;
}

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