#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package RPS::Import::DanceMusicHub::v2;

use strict;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::Client;

use lib '/app/tools/common/lib';
use Common::Consts;
use Common::Assert;
use Common::Log;

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

use lib '/app/tools/rps/lib';
use RPS::Import::SaleRec;
use RPS::DB::Item::MediaType;
use RPS::File::Sale;

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

sub _fieldMap {
    {
        label         => 16, # Q
        country_code  => 14, # O
        date_start    => 1,  # B
        date_end      => 2,  # C
        type          => 6,  # G
        format        => 5,  # F
        artist        => 15, # P
        upc           => 7,  # H
        isrc          => 8,  # I
        title         => 13, # N
        quantity      => 9,  # J
        currency_code => 12, # M
        net_price     => 11, # L
    }
}

sub _productTypeMap {
    {
        'album' =>
        {
            productType => RPS::File::Sale::TYPE_ALBUM,
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'track' =>
        {
            productType => RPS::File::Sale::TYPE_TRACK,
            formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
            mediaType => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
    }
}


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;
    my $productTypeMap = $self->_productTypeMap();

    assert(defined $args{sheets});
    assert(defined $version);

    my $offsets = $self->_fieldMap;
    my $sheet_names = $args{sheet_names};
    my $sheets = $args{sheets};
    my $linenum = 1;


    for (my $sheetIndex = 0; $sheetIndex < scalar @{$args{sheets}}; $sheetIndex++)
    {
        my $sheet = $sheets->[$sheetIndex];

        my $foundHeader = 0;
        for (my $lineIndex = 0; $lineIndex < scalar @$sheet; $lineIndex++)
        {
            $linenum = $lineIndex + 1;
            my $line = $sheet->[$lineIndex];

            if (! $foundHeader)
            {
                if ('EAN / UPC' eq $line->[$offsets->{upc}])
                {
                    $foundHeader = 1;
                }
                next;
            }

            my $country = $line->[$offsets->{country_code}];
            my $currencyCode = $line->[$offsets->{currency_code}];

            my $productType = $line->[$offsets->{type}];

            my $format;
            my $mediaType;

            my $trackTitle;
            my $albumTitle;
            my $upc;
            my $isrc;

            if( $productType =~ /album/i ) {
                $albumTitle = $line->[$offsets->{title}];
                $upc        = $line->[$offsets->{upc}];
            } else {
                $trackTitle = $line->[$offsets->{title}];
                $isrc       = $line->[$offsets->{isrc}];
            }

            my $artist              = $line->[$offsets->{artist}];
            my $label               = $line->[$offsets->{label}];
            my $units               = $line->[$offsets->{quantity}];
            my $netPrice            = $line->[$offsets->{net_price}];

            my $startDate           = _normalizeDate( $line->[$offsets->{date_start}] );
            my $endDate             = _normalizeDate( $line->[$offsets->{date_end}] );

            # Probably wise to allow for blank lines...
            #
            if ($units || $artist || $albumTitle || $trackTitle)
            {
                my $mapping = $productTypeMap->{ lc($productType) };
                if ($mapping)
                {
                    $productType = $mapping->{productType};
                    $format = $mapping->{formatType};
                    $mediaType = $mapping->{mediaType};
                } else {
                    die "Unknown product type: '$productType' line: $linenum";
                }

                my ($dateBegin, $dateEnd) = $self->_getDates(date_begin => $startDate, date_end => $endDate);

                my $unitPrice = $netPrice / $units;

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

                $sale->labelName($label);
                $sale->mediaType($mediaType);
                $sale->productType($productType);
                $sale->formatType($format);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->trackName($trackTitle);
                $sale->albumName($albumTitle);
                $sale->artistName($artist);
                $sale->upc($upc);
                $sale->isrc($isrc);
                $sale->units($units);
                $sale->price($unitPrice);
                $sale->countryCode($country);
                $sale->currencyCode($currencyCode);
                $sale->lineNum($linenum);

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

    return $linenum;
}

# This importer is designed for dates in the format YYYY-MM-DD or DD/MM/YYYY
sub _normalizeDate {
    my($d) = @_;

    my $dt = $d;

    if ( $d =~ m/(\d\d)\/(\d\d)\/(\d\d\d\d)/ ) { # DD/MM/YYYY
       my($day, $month, $year) = ($1, $2, $3);
       $dt = sprintf("%4d-%02d-%02d", $year, $month, $day);
    }

    return $dt;
}

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