package RPS::Import::PanicButton;

use strict;

use Date::Calc qw(Days_in_Month);
use Math::BigFloat;

use lib '/app/tools/common/lib';
use Common::Util;
use Common::Consts qw(%CODE_TO_COUNTRY);

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

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

my %field_map = (
    1 => {
        'date'      => 1,
        'label'     => 2,
        'format'    => 3,
        'prodtype'  => 4,
        'svcprodid' => 5,
        'aartist'   => 6,
        'album'     => 7,
        'tartist'   => 8,
        'track'     => 9,
        'tracknum'  => 10,
        'upc'       => 11,
        'isrc'      => 12,
        'service'   => 13,
        'country'   => 14,
        'free'      => 15,
        'units'     => 16,
        'retail'    => 17,
        'price'     => 18,
    },
    2 => {
        'date'      => 1,
        'label'     => 2,
        'format'    => 3,
        'prodtype'  => 4,
        'svcprodid' => 5,
        'aartist'   => 6,
        'album'     => 7,
        'tartist'   => 8,
        'track'     => 9,
        'upc'       => 10,
        'isrc'      => 11,
        'service'   => 12,
        'country'   => 13,
        'free'      => 14,
        'units'     => 15,
        'retail'    => 16,
        'price'     => 17,
    },
);

#public methods

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

    my $lines = $args{lines};
    return 0 unless ($lines);

    my $fileObj = $args{file};
    my $version = $fileObj->VersionNum;
    my $offsets = $field_map{$version};

    my %errors  = ();
    my $linenum = 1;
    foreach my $line (@$lines) {
        my $label     = $line->[ $offsets->{'label'} ];
        my $svcProdID = $line->[ $offsets->{'svcprodid'} ];
        my $album     = $line->[ $offsets->{'album'} ];
        my $track     = $line->[ $offsets->{'track'} ];
        my $trackNum  = $line->[ $offsets->{'tracknum'} ];
        my $upc       = $line->[ $offsets->{'upc'} ];
        my $isrc      = $line->[ $offsets->{'isrc'} ];
        my $service   = $line->[ $offsets->{'service'} ];
        my $free      = lc $line->[ $offsets->{'free'} ] eq 'y' ? 1 : 0;

        my ($units)  = $line->[ $offsets->{'units'} ];
        my ($retail) = $line->[ $offsets->{'retail'} ];
        my ($price)  = Math::BigFloat->new( $line->[ $offsets->{'price'} ] );

        if ( $units != 0 && defined $price ) {
            if ( $units < 0 || $price < 0 ) {
                $units  *= -1 if ( $units < 0 );
                $price  *= -1 if ( $price < 0 );
                $retail *= -1 if ( $retail < 0 );
                $price  /= $units;
                $retail /= $units;
                $units  *= -1 if ( $units > 0 );
                $price  *= -1 if ( $price < 0 );
                $retail *= -1 if ( $retail < 0 );
            } else {
                $price  /= $units;
                $retail /= $units;
            }
            my $format =
                $line->[ $offsets->{'format'} ] =~ m/permanent/i ? RPS::File::Sale::FORMAT_DOWNLOAD
              : $line->[ $offsets->{'format'} ] =~ m/tethered/i  ? RPS::File::Sale::FORMAT_TETHERED
              : $line->[ $offsets->{'format'} ] =~ m/stream/i    ? RPS::File::Sale::FORMAT_STREAM
              : $line->[ $offsets->{'format'} ] =~ m/ringtone/i  ? RPS::File::Sale::FORMAT_RINGTONE
              :                                                    '';

            #            unless ($format || exists $errors{ $line->[$offsets->{'format'}] })
            #            {
            #                $self->warning();
            #                print STDERR "unknown format: ". $line->[$offsets->{'format'}] ."\n";
            #                $errors{ $line->[$offsets->{'format'}] } = 1;
            #            }

            my $prodType =
              lc $line->[ $offsets->{'prodtype'} ] eq 'a'
              ? RPS::File::Sale::TYPE_ALBUM
              : RPS::File::Sale::TYPE_TRACK;

            my $artist = $prodType eq RPS::File::Sale::TYPE_ALBUM ? $line->[ $offsets->{'aartist'} ] : $line->[ $offsets->{'tartist'} ];

            $line->[ $offsets->{'service'} ] =~ s/virgin digital/virgin/i;
            $line->[ $offsets->{'service'} ] =~ s/APPLE/iTunes/i;
            $line->[ $offsets->{'service'} ] = 'AMAZON' if ( $line->[ $offsets->{'service'} ] =~ m/AMAZON/ );

            my $serviceID = $self->getServiceID( $line->[ $offsets->{'service'} ] );

            #            unless ($serviceID || exists $errors{ $line->[$offsets->{'service'}] })
            #            {
            #                $self->warning();
            #                print STDERR "unknown service: ". $line->[$offsets->{'service'}] ."\n";
            #                $errors{ $line->[$offsets->{'service'}] } = 1;
            #            }

            my $countryCode = uc $line->[ $offsets->{'country'} ];

            #            unless (exists $CODE_TO_COUNTRY{$countryCode} || exists $errors{$countryCode})
            #            {
            #                $self->warning();
            #                print STDERR "unknown country: $countryCode\n";
            #                $errors{$countryCode} = 1;
            #            }

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

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

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

            $sale->productType($prodType);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->countryCode($countryCode);
            $sale->free($free);
            $sale->isrc($isrc);
            $sale->labelName($label);
            $sale->lineNum($linenum);
            $sale->price($price);
            $sale->retail($retail);
            $sale->serviceProductID($svcProdID);
            $sale->serviceID($serviceID);
            $sale->trackName($track);
            $sale->trackNum($trackNum);
            $sale->units($units);
            $sale->upc($upc);

            #$args{dumper}($sale);  ## for cmd-line testing
            $self->_insertSale( sale => $sale );
        }    #else { print STDERR "skip: $linenum u: $units p: $price\n"; }
        $linenum++;
    }

    return %errors ? undef : $linenum;
}

#
# Private methods
#

sub _validateSaleRec {
    my ( $self, $saleRec ) = @_;

    # This importer cares about service_id.
    #
    if ( !$saleRec->serviceID() ) {
        die Import::ValidationError->new( $saleRec, "Unable to identify service" );
    }

    return $self->SUPER::_validateSaleRec($saleRec);
}

sub __getDates {
    my $self    = shift;
    my $dateCol = shift;

    return undef unless ( $dateCol =~ m/^(\d\d\d\d)\D(\d\d)$/ );
    my ( $year, $month ) = ( $1, $2 );

    return (
        Common::Util::normalize_date( join( '-', $year, $month, 1 ) ),
        Common::Util::normalize_date( join( '-', $year, $month, Days_in_Month( $year, $month ) ) ),
    );
}

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