package RPS::Import::SoundBuzz;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_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 RPS::Import::Importer;
use base 'RPS::Import::Importer';

my %format_type = ( D => RPS::File::Sale::FORMAT_DOWNLOAD, );

my %product_type = (
    T => RPS::File::Sale::TYPE_TRACK,
    B => RPS::File::Sale::TYPE_ALBUM,
);

my %all_fields = (
    1 => {
        CountryOfSale         => 'country',
        SalesDate             => 'date',
        BundleOrIndividual    => 'product',
        UPC                   => 'upc',
        ISRC                  => 'isrc',
        TrackArtistName       => 'artist',
        TrackTitle            => 'track',
        TrackLabelName        => 'label',
        AlbumArtistName       => 'album_artist',
        AlbumTitle            => 'album',
        AlbumLabelName        => 'album_label',
        CurrencyType          => 'currency',
        No_OfAudioTransaction => 'units',
        'excl GST'            => 'price',
    },
    2 => {
        CountryOfSale         => 'country',
        SalesDate             => 'date',
        BundleOrIndividual    => 'product',
        UPC                   => 'upc',
        ISRC                  => 'isrc',
        TrackArtistName       => 'artist',
        TruetoneTitle         => 'track',
        LabelName             => 'label',
        'excl GST'            => 'price',
        CurrencyType          => 'currency',
        No_OfAudioTransaction => 'units',
    },
);

#public methods

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

    my $fileObj     = $args{file};
    my $version     = $args{file}->VersionNum();
    my $fileName    = $args{file}->OrigFileName();
    my $serviceID   = $args{file}->ServiceID;
    my $sheet_count = 0;

    return undef unless ( defined $args{sheets} && defined $version );

    my %useful_fields = %{ $all_fields{$version} };
    my $sheet_names   = $args{sheet_names};
    my $header_found  = 0;
    my $linenum       = 1;

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $found_header = 0;
        my $linenum      = 1;
        if ( $sheet_names->[$sheet_count] !~ /summary/i ) {
            my %field_position = ();
            foreach my $line (@$sheet) {
                if ( $found_header == 0 ) {
                    my @columns = @$line if ($line);
                    for ( my $x = 1 ; $x < @columns ; $x++ ) {
                        my @search_fields = keys %useful_fields;
                        for ( my $y = 0 ; $y < @search_fields ; $y++ ) {
                            if ( $columns[$x] =~ /$search_fields[$y]/ ) {
                                $found_header++;
                                $field_position{ $useful_fields{ $search_fields[$y] } } = $x;
                            }
                        }
                    }
                } elsif ( $found_header > 0 ) {

                    my $artist       = $line->[ $field_position{artist} ];
                    my $title        = $line->[ $field_position{track} ];
                    my $country      = uc $line->[ $field_position{country} ];
                    my $format       = RPS::File::Sale::FORMAT_DOWNLOAD;
                    my $prodtype     = $product_type{ $line->[ $field_position{product} ] };
                    my $units        = $line->[ $field_position{units} ];
                    my $price        = $line->[ $field_position{price} ];
                    my $currency     = uc $line->[ $field_position{currency} ];
                    my $isrc         = $line->[ $field_position{isrc} ];
                    my $upc          = $line->[ $field_position{upc} ];
                    my $album        = $line->[ $field_position{album} ] if ( defined $field_position{album} );
                    my $album_artist = $line->[ $field_position{album_artist} ] if ( defined $field_position{album_artist} );
                    my $label        = $line->[ $field_position{label} ];
                    my $album_label  = $line->[ $field_position{album_label} ] if ( defined $field_position{album_label} );
                    $format = RPS::File::Sale::FORMAT_RINGTONE if ( $version == 2 );
                    $artist = $album_artist if ( $artist eq "" && $album_artist ne "" );
                    $price /= $units if ( $units > 1 );
                    $price /= ( $units * -1 ) if ( $units < 0 );
                    $isrc =~ s/\-//g;
                    $isrc =~ s/\_//g;

                    if (   $units
                        && $price
                        && ( $title && $title !~ /title/i || $album && $album !~ /albumtitle/i )
                        && $format
                        && $line->[ $field_position{date} ] ) {
                        my ( $dateBegin, $dateEnd ) = $self->_getDates( $line->[ $field_position{date} ] );

                        unless ( defined $dateBegin && defined $dateEnd ) {
                            print STDERR "Couldn't get dates from: " . $line->[ $field_position{date} ] . "\n";
                            $self->errstr( "couldn't get dates from: " . $fileName . "-" . $sheet_names->[$sheet_count] );
                            return undef;
                        }

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

                        $sale->productType($prodtype);
                        $sale->dateBegin($dateBegin);
                        $sale->dateEnd($dateEnd);
                        $sale->isrc($isrc) if ( $isrc ne "" );
                        $sale->upc($upc)   if ( $upc ne "" );
                        $sale->artistName($artist);
                        $sale->labelName($label)       if ( $label ne "" );
                        $sale->labelName($album_label) if ( $album_label ne "" );
                        $sale->trackName($title)       if ( $title ne "" );
                        $sale->albumName($album)       if ( $album ne "" );
                        $sale->formatType($format);
                        $sale->units($units);
                        $sale->price($price);
                        $sale->countryCode($country);
                        $sale->currencyCode($currency);
                        $sale->lineNum($linenum);

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

#else { print STDERR "skip sh: ".$sheet_names->[$sheet_count] . ": l: " . $linenum . " u:".$units." p:".$price." a:".$artist." t:".$title." f:".$format." d:".$line->[$field_position{date}]."\n"; }
                }
                $linenum++;
            }
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my ( $month, $monthName, $year );
    my $self        = shift;
    my $passed_date = shift;
    if ( $passed_date =~ m/(\d{4})\D(\d+)\D(\d+)/ ) {
        $year  = $1;
        $month = $2;
    } elsif ( $passed_date =~ m/(\d+)\D(\d+)\D(\d{4})/ ) {
        $year  = $3;
        $month = $2;
    }
    if ( $month eq "" ) {
        $monthName = "jan" if ( $passed_date =~ /jan/i );
        $monthName = "feb" if ( $passed_date =~ /feb/i );
        $monthName = "mar" if ( $passed_date =~ /mar/i );
        $monthName = "apr" if ( $passed_date =~ /apr/i );
        $monthName = "may" if ( $passed_date =~ /may/i );
        $monthName = "jun" if ( $passed_date =~ /jun/i );
        $monthName = "jul" if ( $passed_date =~ /jul/i );
        $monthName = "aug" if ( $passed_date =~ /aug/i );
        $monthName = "sep" if ( $passed_date =~ /sep/i );
        $monthName = "oct" if ( $passed_date =~ /oct/i );
        $monthName = "nov" if ( $passed_date =~ /nov/i );
        $monthName = "dec" if ( $passed_date =~ /dec/i );
        $month = Decode_Month($monthName) if ( $month eq "" && $monthName ne "" );
    }

    #print STDERR "|->".$passed_date."<>".$monthName."<>".$month."<>".$year."<-|\n";
    my $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
    my $dateEnd = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
    return ( $dateBegin, $dateEnd );
    return undef;
}

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