package RPS::Import::OrchardDRA;

use strict;

use Date::Calc qw(Days_in_Month);

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

use Common::RSMath qw(round);

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

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

my %service_map = (
    'apple computer, inc.' => Client::Service::DSP_ITUNES,
    'virginmega sas'       => Client::Service::DSP_VIRGINMEGA,
    'touch tunes, inc.'    => Client::Service::DSP_TOUCHTUNES,
    'hudson entertainment' => Client::Service::DSP_HUDSON,
    'itunes canada'        => Client::Service::DSP_ITUNES,
);

my %field_map = (
    4 => {
        vendor_id   => 0,
        artist      => 1,
        track       => 2,
        album       => 3,
        isrc        => 4,
        upc         => 5,
        start_col   => 50,
        format_row  => 2,
        service_row => 3,
    },
    5 => {
        vendor_id   => 0,
        artist      => 1,
        track       => 2,
        album       => 3,
        isrc        => 4,
        upc         => 5,
        start_col   => 46,
        format_row  => 2,
        service_row => 3,
    },
    6 => {
        vendor_id   => 0,
        artist      => 1,
        track       => 2,
        album       => 3,
        isrc        => 4,
        upc         => 5,
        start_col   => 55,
        format_row  => 2,
        service_row => 3,
    },
    10 => {
        vendor_id   => 0,
        artist      => 1,
        track       => 2,
        album       => 3,
        isrc        => 4,
        upc         => 5,
        start_col   => 24,
        format_row  => 2,
        service_row => 3,
    },
    11 => {
        vendor_id   => 0,
        artist      => 1,
        track       => 2,
        album       => 3,
        isrc        => 4,
        upc         => 5,
        start_col   => 26,
        format_row  => 2,
        service_row => 3,
    },
    12 => {
        vendor_id   => 0,
        artist      => 1,
        track       => 2,
        album       => 3,
        isrc        => 4,
        upc         => 5,
        start_col   => 22,
        format_row  => 2,
        service_row => 3,
    },
);

#public methods

sub _importLines {
    my $self     = shift;
    my %args     = @_;
    my $fileObj  = $args{file};
    my $version  = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();
    my $lines    = $args{lines};
    my $offsets  = $field_map{$version};
    return undef unless ( defined $args{lines} && defined $version );

    my ( $dateBegin, $dateEnd ) = $self->_getDates($fileName);

    unless ( $dateBegin && $dateEnd ) {
        print STDERR "Couldn't get date from " . $fileName . "\n";
        $self->errstr( "couldn't get dates from " . $fileName );
        return undef;
    }

    my %errors;
    my $start_col          = 0;
    my $linenum            = 1;
    my $download_start     = 0;
    my $ringtone_start     = 0;
    my $subscription_start = 0;
    my $ota_start          = 0;
    my $services;
    my %formats;

    foreach my $line (@$lines) {
        if ( $linenum == $offsets->{service_row} ) {
            my @columns = @$line;
            for ( my $ccount = $offsets->{start_col} ; $ccount < @columns ; $ccount++ ) {
                my ( $country, $serviceName ) = _getService( $columns[$ccount] );
                $services->[$ccount]->{country} = $country;
                $services->[$ccount]->{ID}      = $self->getServiceID($serviceName);
                $services->[$ccount]->{ID}      = $service_map{ lc $serviceName } if ( $services->[$ccount]->{ID} eq "" );

                if ( $services->[$ccount]->{ID} eq "" ) {
                    $self->errstr( "Could not find service from: " . $columns[$ccount] );
                    print STDERR "Could not find service from: " . $columns[$ccount] . "\n";
                    return undef;
                }
                if ( $services->[$ccount]->{country} eq "" ) {
                    $self->errstr( "Could not find country from: " . $columns[$ccount] );
                    print STDERR "Could not find country from: " . $columns[$ccount] . "\n";
                    return undef;
                }
                $ccount++;
            }
        } elsif ( $linenum == $offsets->{format_row} ) {
            my @columns = @$line;
            %formats = ();
            for ( my $ccount = $offsets->{start_col} ; $ccount < @columns ; $ccount++ ) {
                $formats{download}->{start}      = $ccount if ( $columns[$ccount] =~ /download/i );
                $formats{download}->{format}     = RPS::File::Sale::FORMAT_DOWNLOAD;
                $formats{ota}->{start}           = $ccount if ( $columns[$ccount] =~ /ota/i );
                $formats{ota}->{format}          = RPS::File::Sale::FORMAT_DOWNLOAD;
                $formats{subscription}->{start}  = $ccount if ( $columns[$ccount] =~ /subscription/i );
                $formats{subscription}->{format} = RPS::File::Sale::FORMAT_STREAM;
                $formats{ringtone}->{start}      = $ccount if ( $columns[$ccount] =~ /ringtone/i );
                $formats{ringtone}->{format}     = RPS::File::Sale::FORMAT_RINGTONE;
            }
        } elsif ( $linenum > $offsets->{service_row} ) {

            my $ptype     = RPS::File::Sale::TYPE_TRACK;
            my $artist    = $line->[ $offsets->{'artist'} ];
            my $album     = $line->[ $offsets->{'album'} ];
            my $track     = $line->[ $offsets->{'track'} ];
            my $vendor_id = $line->[ $offsets->{'vendor_id'} ];
            my $upc       = Common::Util::normalize_upc( $line->[ $offsets->{'upc'} ] );
            my $isrc      = Common::Util::normalize_isrc( $line->[ $offsets->{'isrc'} ] );
            my @columns   = @$line;
            for ( my $ccount = $offsets->{start_col} ; $ccount < @columns ; $ccount++ ) {

                if ( $ccount == $formats{download}->{start} ) {
                    $download_start++;
                    $ringtone_start     = 0;
                    $ota_start          = 0;
                    $subscription_start = 0;
                } elsif ( $ccount == $formats{ringtone}->{start} ) {
                    $download_start = 0;
                    $ringtone_start++;
                    $ota_start          = 0;
                    $subscription_start = 0;
                } elsif ( $ccount == $formats{subscription}->{start} ) {
                    $download_start = 0;
                    $ringtone_start = 0;
                    $ota_start      = 0;
                    $subscription_start++;
                } elsif ( $ccount == $formats{ota}->{start} ) {
                    $download_start = 0;
                    $ringtone_start = 0;
                    $ota_start++;
                    $subscription_start = 0;
                }

                my $format;
                $format = RPS::File::Sale::FORMAT_DOWNLOAD if ( $download_start > 0 || $ota_start > 0 );
                $format = RPS::File::Sale::FORMAT_STREAM   if ( $subscription_start > 0 );
                $format = RPS::File::Sale::FORMAT_RINGTONE if ( $ringtone_start > 0 );
                my $serviceID = $services->[$ccount]->{ID};
                my $country   = $services->[$ccount]->{country};
                my $units     = $line->[$ccount];
                my $price     = $line->[ $ccount + 1 ];
                $price =~ s/^\$//g;
                $price =~ s/\,//g;
                $price /= $units if ( $units > 1 );

                if ( $units && $track && $artist && $album && $serviceID && $country && $format ) {
                    my $sale = RPS::Import::SaleRec->new();

                    $sale->serviceID($serviceID);
                    $sale->productType($ptype);
                    $sale->formatType($format);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->serviceProductID($vendor_id);
                    $sale->upc($upc);
                    $sale->isrc($isrc);
                    $sale->artistName($artist);
                    $sale->albumName($album);
                    $sale->trackName($track);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->currencyCode("USD");
                    $sale->lineNum($linenum);
                    $sale->countryCode($country);

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

                $ccount++;
            }
        }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $self = shift;
    my $date = shift;

    my ( $dateBegin, $dateEnd );
    if ( $date =~ m/(\d{4})-(\d+)-(\d+)_to_(\d{4})-(\d+)-(\d+)/ ) {
        my $dateBegin = sprintf( "%04d-%02d-%02d", $1, $2, $3 );
        my $dateEnd   = sprintf( "%04d-%02d-%02d", $4, $5, $6 );
        return ( $dateBegin, $dateEnd );
    }

    return undef;
}

sub _getService {
    my $serviceCell = shift;
    my $country;
    if ( $serviceCell =~ /germany/i ) {
        $country = "DE";
        $serviceCell =~ s/\(germany\)//i;
        $serviceCell =~ s/ germany//i;
    }
    if ( $serviceCell =~ /UK/ ) {
        $country = "GB";
        $serviceCell =~ s/ UK//;
    }
    if ( $serviceCell =~ /US/ ) {
        $country = "US";
        $serviceCell =~ s/ US//;
    }
    if ( $serviceCell =~ /australia/i ) {
        $country = "AU";
        $serviceCell =~ s/ australia//i;
    }
    if ( $serviceCell =~ /canada/i ) {
        $country = "CA";
        $serviceCell =~ s/ Canada//;
    }
    if ( $serviceCell =~ /zealand/i ) {
        $country = "NZ";
        $serviceCell =~ s/ New Zealand//;
    }
    if ( $serviceCell =~ / S\.a\.r\.l\./i ) {
        $country = "EU";
        $serviceCell =~ s/ S\.a\.r\.l\.//;
    }
    if ( $serviceCell =~ /EU/ ) {
        $country = "EU";
        $serviceCell =~ s/ EU//;
    }
    if ( $serviceCell =~ /switzerland/i ) {
        $country = "CH";
        $serviceCell =~ s/ switzerland//i;
    }
    if ( $country eq "" ) {
        $country = "US";
    }
    return ( $country, $serviceCell );
}

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