package RPS::Import::ShockHound;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

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

use lib '/app/tools/data_classes/lib';
use Client::Service;

my %field_map = (
    1 => {
        'date'     => 3,
        'album'    => 5,
        'album_id' => 6,
        'upc'      => 8,
        'label'    => 11,
        'artist'   => 13,
        'track'    => 14,
        'track_id' => 15,
        'tracknum' => 16,
        'isrc'     => 17,
        'product'  => 19,
        'currency' => 20,
        'country'  => 21,
        'units'    => 24,
        'price'    => 27,
    },
    2 => {
        'date'     => 1,
        'album'    => 5,
        'album_id' => 6,
        'upc'      => 9,
        'label'    => 11,
        'artist'   => 14,
        'track'    => 15,
        'track_id' => 16,
        'tracknum' => 17,
        'isrc'     => 18,
        'product'  => 21,
        'currency' => 22,
        'country'  => 23,
        'units'    => 26,
        'price'    => 29,
    },
    3 => {
        'date'     => 0,
        'album'    => 5,
        'upc'      => 7,
        'label'    => 10,
        'artist'   => 12,
        'track'    => 13,
        'track_id' => 14,
        'tracknum' => 15,
        'isrc'     => 16,
        'product'  => 19,
        'currency' => 20,
        'country'  => 21,
        'units'    => 24,
        'price'    => 27,
    },
    5 => {
        'date'     => 0,
        'album'    => 5,
        'upc'      => 9,
        'label'    => 11,
        'artist'   => 14,
        'track'    => 15,
        'track_id' => 16,
        'tracknum' => 17,
        'isrc'     => 18,
        'product'  => 21,
        'currency' => 22,
        'country'  => 23,
        'units'    => 26,
        'price'    => 31,
    },
);

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

#public methods

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

    my $retval   = undef;
    my $lines    = $args{lines};
    my $fileObj  = $args{file};
    my $fileName = $fileObj->OrigFileName;
    my $version  = $fileObj->VersionNum;

    return undef unless ( $lines && $fileName && $version );

    my $offsets = $field_map{$version};

    my %errors  = ();
    my $linenum = 1;

    my $defaultDate;
    my $defaultDateBegin;
    my $defaultDateEnd;
    my $headerFound;

    foreach my $line (@$lines) {
        $defaultDate = $line->[0];
        if ( $defaultDate =~ m/Reporting Period/ ) {
            my ( $f_defaultDateBegin, $f_defaultDateEnd ) =
              split( "-", $defaultDate );
            if ( $defaultDate =~ /\d{4}\D\d{2}\D\d{2}/ ) {

                ( $defaultDateBegin, $defaultDateEnd ) = $self->_getDates(
                    date_begin => $f_defaultDateBegin,
                    date_end   => $f_defaultDateEnd,
                    type       => "iso"
                );
            } elsif ( $defaultDate =~ /\d{1,2}\D\d{1,2}\D\d{2}/ ) {
                print STDERR "Default date US: $defaultDate at line num: $linenum\n";

                my ( $monthBegin, $monthEnd, $yearBegin, $yearEnd );

                if ( $f_defaultDateBegin =~ /(\d{1,2})\D\d{1,2}\D(\d{4})/ ) {
                    $monthBegin = sprintf( "%02d", $1 );
                    $yearBegin = $2;
                } elsif ( $f_defaultDateBegin =~ /(\d{1,2})\D\d{1,2}\D(\d{2})/ ) {
                    $monthBegin = sprintf( "%02d", $1 );
                    $yearBegin = $2;
                }

                if ( $f_defaultDateBegin =~ /(\d{1,2})\D\d{1,2}\D(\d{4})/ ) {
                    $monthEnd = sprintf( "%02d", $1 );
                    $yearEnd = $2;
                } elsif ( $f_defaultDateBegin =~ /(\d{1,2})\D\d{1,2}\D(\d{2})/ ) {
                    $monthEnd = sprintf( "%02d", $1 );
                    $yearEnd = $2;
                }

                ( $defaultDateBegin, $defaultDateEnd ) = $self->_getDates(
                    date_begin => "$monthBegin/01/$yearBegin",
                    date_end   => "$monthEnd/01/$yearEnd",
                    type       => "us"
                );

                print STDERR "Extracted $f_defaultDateBegin, $f_defaultDateEnd\n";

                print STDERR "Default dates in US: $defaultDateBegin," . "$defaultDateEnd\n";
            }
        }

        unless ($headerFound) {
            if ( $line->[ $offsets->{'product'} ] eq 'Purchasable Type' ) {
                $headerFound = 1;
            }

            $linenum++;
            next;
        }

        my $format = RPS::File::Sale::FORMAT_DOWNLOAD;

        my $prodtype;
        my $serviceID;

        if ( $line->[ $offsets->{'product'} ] eq 'Track' ) {
            $prodtype  = RPS::File::Sale::TYPE_TRACK;
            $serviceID = $line->[ $offsets->{'track_id'} ];
        } elsif ( $line->[ $offsets->{'product'} ] eq 'Album' ) {
            $prodtype = RPS::File::Sale::TYPE_ALBUM;
            $serviceID = $line->[ $offsets->{'album_id'} ] unless ( $version == 3 || $version == 5 );
        }

        my $upc          = Common::Util::normalize_upc( $line->[ $offsets->{'upc'} ] );
        my $isrc         = Common::Util::normalize_isrc( $line->[ $offsets->{'isrc'} ] );
        my $artist       = $line->[ $offsets->{'artist'} ];
        my $album        = $line->[ $offsets->{'album'} ];
        my $track        = $line->[ $offsets->{'track'} ];
        my $label        = $line->[ $offsets->{'label'} ];
        my $units        = $line->[ $offsets->{'units'} ];
        my $countryCode  = $line->[ $offsets->{'country'} ];
        my $currencyCode = $line->[ $offsets->{'currency'} ];
        my $tracknum     = $line->[ $offsets->{'tracknum'} ];
        my $price        = $line->[ $offsets->{'price'} ];
        if ($price) {
            $price = sprintf( "%.8f", $price );
        }

        if ( $prodtype && $units && ( $artist || $album || $track ) ) {

            #print STDERR "passing date: $line->[$offsets->{date}] for line $linenum\n";
            my ( $dateBegin, $dateEnd );

            if ( $line->[ $offsets->{date} ] =~ /\d{4}\D\d{2}\D\d{2}/ ) {
                ( $dateBegin, $dateEnd ) =
                  $self->_getDates( date_begin => $line->[ $offsets->{date} ], type => "iso" );
            } elsif ( $line->[ $offsets->{date} ] =~ /(\d{1,2})\D\d{1,2}\D(\d{2,4})/ ) {
                my $monthBegin = sprintf( "%02d", $1 );

                ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => "$monthBegin/01/$2", type => "us" );
            }

            unless ( $dateBegin && $dateEnd ) {
                ( $dateBegin, $dateEnd ) = ( $defaultDateBegin, $defaultDateEnd );
                unless ( $dateBegin && $dateEnd ) {
                    print STDERR "Couldn't get dates from '" . $line->[ $offsets->{date} ] . "' (line: $linenum)\n";
                    $self->errstr(
                        "couldn't get dates from '" . $line->[ $offsets->{date} ] . "' (line: $linenum) -- default date is $defaultDate;" );
                    return undef;
                }
            }

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

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->upc($upc);
            $sale->isrc($isrc) if ( $prodtype eq RPS::File::Sale::TYPE_TRACK );
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->trackName($track) if ( $prodtype eq RPS::File::Sale::TYPE_TRACK );
            $sale->labelName($label);
            $sale->units($units);
            $sale->currencyCode($currencyCode);
            $sale->countryCode($countryCode);
            $sale->trackNum($tracknum);
            $sale->price($price);
            $sale->serviceProductID($serviceID);
            $sale->lineNum($linenum);

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

            #print STDERR "product type: $prodtype units: $units artist: $artist album: $album track: $track\n";
        }
        $linenum++;
    }

    die "Header not found." unless ($headerFound);

    return $linenum;
}

#
# Private methods
#

#sub _getDates
#{
#    my ($syear,$eyear,$smonth,$emonth,$passed_date,$dateBegin,$dateEnd);
#    $passed_date = shift;
#    print "$passed_date\n";
#    if ($passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/)
#    {
#            return ($3."-".sprintf("%02d",$1)."-01",$3."-".sprintf("%02d",$1)."-".Days_in_Month($3,$1));
#    }
#    elsif ($passed_date =~ m/(\d{4})(\d{2})(\d{2})/)
#    {
#        return ($1."-".$2."-01",$1."-".$2."-".Days_in_Month($1,$2));
#    }
#    elsif ($passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/)
#    {
#            return ($1."-".sprintf("%02d",$2)."-01",$1."-".sprintf("%02d",$2)."-".Days_in_Month($1,$2));
#    }
#    elsif ($passed_date =~ m/(\d+)\D(\d+)\D(\d{2})/)
#    {
#    				my $year = "20".$3;
#        		return ($year."-".sprintf("%02d",$1)."-01",$year."-".sprintf("%02d",$1)."-".Days_in_Month($year,$1));
#    }
#    return undef;
#}

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