package RPS::Import::LiquidAudio;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

use lib '/app/tools/common/lib';
use Common::Util;
use Common::Consts;

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

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

# field mappings
my %fieldMap = (
    1 => {
        DATE_ROW  => 7,
        DATE      => 0,
        SUMMARY   => 9,
        LABEL     => 0,
        ARTIST    => 1,
        TITLE     => 2,
        UPC       => 3,
        ISRC      => 4,
        CLIENTID  => 5,
        VENDORID  => 6,
        UNITS     => 7,
        PRICE     => 8,
        NUMTRACKS => 10,
    },
    2 => {
        DATE_ROW  => 3,
        DATE      => 0,
        SUMMARY   => 8,
        LABEL     => 0,
        ARTIST    => 1,
        TITLE     => 2,
        UPC       => 3,
        ISRC      => 4,
        CLIENTID  => 5,
        VENDORID  => 5,
        UNITS     => 6,
        PRICE     => 7,
        NUMTRACKS => 9,
    },
    4 => {
        DATE_ROW => 3,
        DATE     => 0,
        SUMMARY  => 8,
        LABEL    => 0,
        ARTIST   => 1,
        ALBUM    => 2,
        TITLE    => 3,
        UPC      => 4,
        ISRC     => 5,
        CLIENTID => 6,
        VENDORID => 7,
        UNITS    => 8,
        PRICE    => 10,
    },
);

#public methods

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

    my $lines   = $args{lines} || return undef;
    my $fileObj = $args{file};
    my $version = $fileObj->VersionNum;
    my $sheets  = $args{sheets};
    return 0 unless ( $version && exists $fieldMap{$version} );

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

    foreach my $sheet (@$sheets) {

        $sheetnum++;

        my $offsets = $fieldMap{$version};
        my ( $rate, $dateBegin, $dateEnd ) = $self->_get_rate_n_dates( $version, $sheet, $offsets, $sheetnum );

        if ( $rate eq "BLANK SHEET" ) {
            next;
        }

        unless ( $rate && $dateBegin && $dateEnd ) {
            $self->errstr("couldn't get dates and/or rate");
            return undef;
        }
        print STDERR "using rate $rate\n";

        $linenum = 1;

        foreach my $line (@$sheet) {
            my $prodtype;

            if ( $version == 4 ) {

                if ( !$line->[ $offsets->{ALBUM} ] ) {
                    $prodtype = RPS::File::Sale::TYPE_ALBUM;
                } else {
                    $prodtype = RPS::File::Sale::TYPE_TRACK;
                }
            } else {

                # if(!defined $offsets->{NUMTRACKS} && $line->[$offsets->{ISRC}] ne "") {
                #    $prodtype = RPS::File::Sale::TYPE_TRACK;
                #}
                #elsif(!defined $offsets->{NUMTRACKS}) {
                #   $prodtype = RPS::File::Sale::TYPE_ALBUM;
                #}
                if (   $line->[ $offsets->{TITLE} ] =~ /\[full album download\]\s*$/i
                    || $line->[ $offsets->{NUMTRACKS} ] > 1 ) {
                    $prodtype = RPS::File::Sale::TYPE_ALBUM;
                } elsif ( $line->[ $offsets->{NUMTRACKS} ] == 1 ) {
                    $prodtype = RPS::File::Sale::TYPE_TRACK;
                }
            }

            my $format   = RPS::File::Sale::FORMAT_DOWNLOAD;
            my $vendorID = $line->[ $offsets->{VENDORID} ];
            my $clientID = $line->[ $offsets->{CLIENTID} ];
            my $upc      = Common::Util::normalize_upc( $line->[ $offsets->{UPC} ] );
            my $isrc     = Common::Util::normalize_isrc( $line->[ $offsets->{ISRC} ] );
            my $artist   = $line->[ $offsets->{ARTIST} ];
            my $title    = $line->[ $offsets->{TITLE} ];
            my $album    = $line->[ $offsets->{ALBUM} ] if ( defined $offsets->{NUMTRACKS} );

            my $album;
            my $track;

            if ( $prodtype eq RPS::File::Sale::TYPE_ALBUM ) {
                ( $album = $title ) =~ s/\s*\[full album download\]\s*$//i;
            } elsif ( $prodtype eq RPS::File::Sale::TYPE_TRACK ) {
                $album = $line->[ $offsets->{ALBUM} ] if ( defined $offsets->{ALBUM} );
                $album =~ s/\s*\[full album download\]\s*$//i;
                $track = $title;
            }

            my $label = $line->[ $offsets->{LABEL} ];
            my ($units) = $line->[ $offsets->{UNITS} ] =~ m/^(-?\d+)$/;

            # If the cell is formatted as currency, ParseExcel may prepend "[$$49]"
            # to the actual price.  This needs to be removed..
            #
            my $_price = $line->[ $offsets->{PRICE} ];
            if ( $_price =~ /\[\$\$49\]/ ) {
                $_price =~ s/\[\$\$49\]//;
            }
            my ($price) = $_price =~ m/^[\$]?(-?\d*\.?\d*)$/;

            $price /= $units if ( $units != 0 && $version > 3 );
            $price *= -1 if ( $price < 0 && $units < 0 );

            if ( $prodtype && $units && $price && $artist && $title ) {
                $price *= $rate;
                my $sale = RPS::Import::SaleRec->new();

                $sale->productType($prodtype);
                $sale->formatType($format);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->serviceProductID($vendorID);
                $sale->clientProductID($clientID);
                $sale->upc($upc);
                $sale->isrc($isrc);
                $sale->artistName($artist);
                $sale->albumName($album);
                $sale->trackName($track);
                $sale->labelName($label);
                $sale->units($units);
                $sale->price($price);
                $sale->lineNum($linenum);
                $sale->countryCode('US');

                $self->_insertSale( sale => $sale );
            }    # else { print STDERR "skip: l:$linenum, ptype($prodtype) u($units) p($price) a($artist) t($title)\n"; }
            $linenum++;
        }
    }

    return $linenum;
}

#
# Private methods
#

sub _get_rate_n_dates {
    my ( $self, $version, $lines, $offsets, $sheetnum ) = @_;
    my $summaryField = $offsets->{SUMMARY};
    my ( $rate, $dBeg, $dEnd );

    my $total   = 0;
    my $linenum = 1;

    my @line_array = @$lines;

    my $line_size = @line_array;

    if ( ( !$line_array[ $offsets->{DATE_ROW} ]->[ $offsets->{DATE} ] ) && ( $sheetnum > 1 ) ) {
        return ( "BLANK SHEET", "BLANK SHEET", "BLANK SHEET" );
    }

    foreach my $line (@$lines) {
        if ( ( $linenum == $offsets->{DATE_ROW} ) || ( $linenum == ( $offsets->{DATE_ROW} - 1 ) ) ) {
            my ( $month, $year );
            if ( $version == 1 ) {
                ( $month, $year ) = $line->[ $offsets->{DATE} ] =~ /^\d{8} to (\d\d)\d\d(\d\d\d\d)$/;
                $dBeg = sprintf( "%04d-%02d-01", $year, $month );
                $dEnd = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
            } elsif ( $version == 2 ) {
                if ( $line->[ $offsets->{DATE} ] =~ /^(\w+)\s+(\d{4})$/ ) {
                    $month = Decode_Month($1);
                    $year  = $2;
                } else {
                    ( $month, $year ) = $line->[ $offsets->{DATE} ] =~ /^\d{8} to (\d\d)\d\d(\d\d\d\d)$/;
                }
                $dBeg = sprintf( "%04d-%02d-01", $year, $month );
                $dEnd = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
            } elsif ( $line->[ $offsets->{DATE} ] =~ m/(\d+)\D(\d+)\D(\d{4}) to (\d+)\D(\d+)\D(\d{4})/ ) {
                my $rawDB = sprintf( "%04d-%02d-%02d", $3, $1, $2 );
                my $rawDE = sprintf( "%04d-%02d-%02d", $6, $4, $5 );

                ( $dBeg, $dEnd ) = $self->SUPER::_getDates( date_begin => $rawDB, date_end => $rawDE, type => "iso" );
            }

        } elsif ( $line->[ $offsets->{SUMMARY} ] =~ /\d+(\.\d+)?$/i && defined $offsets->{SUMMARY} ) {
            if ( $line->[ $offsets->{SUMMARY} - 1 ] =~ /commission/i ) {
                $rate = $line->[ $offsets->{SUMMARY} ];
            } elsif ( $line->[ $summaryField - 1 ] =~ /\d+(\.\d+)?$/ ) {
                $total += $line->[ $offsets->{SUMMARY} ];
            }

        }
        $linenum++;
    }

    unless ( $total > 0 ) {
        print STDERR "invalid total '$total'\n";
        return 0;
    }

    $rate =~ s/^-//;
    $rate = $rate == 0 ? 1 : 1 - $rate / $total;

    return ( $rate, $dBeg, $dEnd );
}

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