package RPS::Import::IRIS;

use strict;

use Date::Calc qw(Days_in_Month);

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

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

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

use constant FIELD_TITLE     => 0;
use constant FIELD_ARTIST    => 2;
use constant FIELD_ISRC      => 1;
use constant FIELD_UNITPRICE => 3;
use constant FIELD_UNITS     => 4;
use constant FIELD_COUNTRY   => 5;
use constant FIELD_PRICE     => 10;

my %delivery_formats = (
    'Download'              => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Stream'                => RPS::File::Sale::FORMAT_STREAM,
    'Limited Download'      => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Over the Air Download' => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Ringtone'              => RPS::File::Sale::FORMAT_RINGTONE,
    'Ringback'              => RPS::File::Sale::FORMAT_RINGBACK,
    'Over the Air Download' => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Burn'                  => RPS::File::Sale::FORMAT_DOWNLOAD,
    'Other'                 => RPS::File::Sale::FORMAT_STREAM,
    'Play'                  => RPS::File::Sale::FORMAT_STREAM,
    'Realtone'              => RPS::File::Sale::FORMAT_RINGTONE,
);

#
# public methods
#

sub _importLines {
    my $self  = shift;
    my %args  = @_;
    my $lines = $args{lines};
    return undef unless ($lines);

    #my $version = $args{version}; # cmd-line testing
    my $version = $args{file}->VersionNum();

    #my $fileName = $args{OrigFileName}; # cmd-line testing
    my $fileName = $args{file}->OrigFileName();

    my $format          = RPS::File::Sale::FORMAT_DOWNLOAD;
    my $linenum         = 1;
    my $was_album_title = 0;
    my ( %errors, $passed_format, $album, $dateBegin, $dateEnd, $total_columns, $fee_percentage );
    my $country = "US";
    foreach my $line (@$lines) {
        my $artist = $line->[FIELD_ARTIST];
        my $isrc   = $line->[FIELD_ISRC];
        my $title  = $line->[FIELD_TITLE];

        if ( $line->[0] =~ /Statement Date/i ) {
            ( $dateBegin, $dateEnd ) = _get_dates( $line->[FIELD_ISRC] );
            unless ( $dateBegin && $dateEnd ) {
                $self->errstr( "couldn't get dates from:" . $line->[FIELD_ISRC] );
                print STDERR "couldn't get dates from:" . $line->[FIELD_ISRC] . "\n";
                return undef;
            }
        } elsif ( $line->[0] =~ /percent split/i ) {
            $fee_percentage = $line->[1];
            $fee_percentage =~ s/\D//g;
            $fee_percentage *= .01;
        } elsif ( $artist eq "Artist" && $isrc eq "UPC/ISRC" && $title eq "" ) {
            $passed_format = $line;
        } elsif ( $artist ne "" ) {
            if ( $title =~ /(\d{4})\:\s([a-zA-Z])/ ) {
                $album = $title;
                $album =~ s/^.*[^:]:\s//;
                $was_album_title = 1;
            }
            if ( $artist ne "" && $album ne "" ) {
                $title = $line->[FIELD_TITLE];
                for ( my $x = 0 ; $x < @$line ; $x++ ) {
                    if (   ( $$passed_format[$x] !~ /Artist|UPC\/ISRC|Gross|Fee|Net/ )
                        && ( $$passed_format[$x] ne "" )
                        && ( $line->[ $x + 1 ] != 0 ) ) {
                        my $units = $line->[$x];
                        $units =~ m/^(\d+)$/;
                        my $price = sprintf( "%.8f", ( $line->[ $x + 1 ] / $units ) );
                        my $fee   = sprintf( "%.8f", ( $price * $fee_percentage ) );
                        $price -= sprintf( "%.8f", $fee );
                        my $unitPrice = $price;
                        my $format    = $delivery_formats{ $$passed_format[$x] };
                        my $sale      = RPS::Import::SaleRec->new();

                        if ( $was_album_title == 1 ) {
                            $sale->productType(RPS::File::Sale::TYPE_ALBUM);
                            $sale->upc($isrc);
                        } else {
                            $sale->productType(RPS::File::Sale::TYPE_TRACK);
                            $sale->trackName($title);
                            $sale->isrc($isrc);
                        }
                        $sale->albumName($album);
                        $sale->formatType($format);
                        $sale->dateBegin($dateBegin);
                        $sale->dateEnd($dateEnd);
                        $sale->artistName($artist);
                        $sale->price($price);
                        $sale->units($units);
                        $sale->countryCode($country);
                        $sale->lineNum($linenum);

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

                    #else { print STDERR "skip: ". join(',', @$line) . "\n"; }
                }
            }
            $was_album_title = 0;
        }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _get_dates {
    my $passed_date = shift;
    my ( $month, $year );
    if ( $passed_date =~ m/(\d+)\D(\d{4})/ ) {
        $month = $1;
        $year  = $2;
    } elsif ( $passed_date =~ /\// ) {
        ( $month, $year ) = split( "\/", $passed_date );
    }
    if ( $month ne "" && $year ne "" ) {
        return ( $year . "-" . sprintf( "%02d", $month ) . "-01",
            $year . "-" . sprintf( "%02d", $month ) . "-" . Days_in_Month( $year, $month ) );
    } else {
        return undef;
    }
}

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