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

package RPS::Import::Bandcamp::v1;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_Month);
use Data::Dumper;

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

use lib '/app/tools/common/lib';
use Common::Util qw(normalize_upc normalize_isrc);
use Common::Consts;
use Common::Assert;
use Common::Log;

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

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

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

sub _fieldMap {
    {
        dateBegin   => 'A',
        dateEnd     => 'A',
        productType => 'B',
        formatType  => 'D',
        artistName  => 'E',
        upc         => 'F',
        albumName   => 'C',
        isrc        => 'G',
        trackName   => 'C',
        units       => 'I',
        price       => 'H',
    };
}

sub _importLines {
    my $self        = shift;
    my %args        = @_;
    my $fileObj     = $args{file};
    my $sheet_count = 0;

    assert( defined $args{sheets} );

    my $sheet_names = $args{sheet_names};
    my $sheets      = $args{sheets};
    my $linenum     = 1;
    my $service     = Client::Service::DSP_BANDCAMP;

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

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

            my $dateBegin   = $self->_getByFieldName('dateBegin');
            my $productType = $self->_getByFieldName('productType');
            my $formatType  = $self->_getByFieldName('formatType');
            my $albumName   = $self->_getByFieldName('albumName');

            # this sales file has 4 types of lines:
            #       1) the file header
            #       2) a header for a block of records containing the artistname
            #       3) one or more sales records
            #       4) blank lines separating blocks of sales records

            # if the line is blank, ignore.  Unless....
            if (   !$dateBegin
                && !$productType
                && !$formatType ) {
                Common::Log::Debug("Found Blank Line $albumName");

                # if we're processing a service block, reset the foundArtistName
                # and inTheSales variables
                if ( $foundArtistName && $inTheSales ) {
                    $foundArtistName = 0;
                    $inTheSales      = 0;
                    Common::Log::Debug("Ending a service block");
                }
            }

            # Check for the file header
            if ( !$foundHeader ) {
                if ( $dateBegin =~ m/(order.*date|band)/i ) {
                    $foundHeader = 1;
                    Common::Log::Debug("Found Header");
                }
                next;
            }

            # check of they are reporting an artist name, but no sales data for that artist
            if ( $dateBegin eq "No report" ) {
                next;
            }

            # if we haven't found the artist header, yet
            if ( !$foundArtistName ) {

                # check if the date field is populated with a non-date and that there's
                # no productType value.  Then that's a servieName
                if (   !( $dateBegin =~ m/\d{1,2}\/\d{1,2}\/\d{2}/ )
                    && !( $dateBegin =~ m/\d{4}-\d{2}-\d{2}/ )
                    && $dateBegin
                    && ( !$productType || $productType eq '' ) ) {
                    $foundArtistName = 1;
                }
                next;

                # we've found a block, now check for valid record values
            } else {

                # date is in M(M)/D(D)/YY format, with months and days not normalized to two digits
                # !!! Now date is coming through in YYYY-MM-DD format
                my $year;
                my $month;

                if ( $dateBegin =~ m/(\d{1,2})\/(\d{1,2})\/(\d{2})/ ) {
                    $inTheSales = 1;

                    #start assembling the sale info to insert
                    $year  = 2000 + $3;
                    $month = $1;

                } elsif ( $dateBegin =~ m/(\d{4})-(\d{2})-\d{2}/ ) {
                    $inTheSales = 1;

                    #start assembling the sale info to insert
                    $year  = $1;
                    $month = $2;
                }

                if ( $year && $month ) {
                    my $dateBeginStr = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
                    my $dateEndStr = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );

                    $productType = RPS::File::Sale::TYPE_TRACK if ( lc($productType) eq 'track' );
                    $productType = RPS::File::Sale::TYPE_ALBUM if ( lc($productType) eq 'album' );
                    if ( lc($productType) eq 'refund' ) {
                        my $isrc = $self->_getByFieldName('isrc');
                        if ( $isrc ) {
                            $productType = RPS::File::Sale::TYPE_TRACK;
                        }
                        else {
                            $productType = RPS::File::Sale::TYPE_ALBUM;
                        }
                    }

                    $formatType = RPS::File::Sale::FORMAT_DOWNLOAD if ( lc($formatType) eq 'digital download' );
                    my $artistName = $self->_getByFieldName('artistName');
                    my $upc        = $self->_getByFieldName('upc');
                    $upc = normalize_upc($upc) if ($upc);

                    my $albumName = $self->_getByFieldName('albumName');
                    my $trackName = $self->_getByFieldName('trackName');

                    my $isrc = $self->_getByFieldName('isrc');
                    $isrc = normalize_isrc($isrc) if ($isrc);

                    my $units = int($self->_getByFieldName('units'));
                    my $price = $self->_getByFieldName('price');
                    $price =~ s/\$//g;

                    # insert the sale record
                    my $sale = RPS::Import::SaleRec->new();

                    $sale->lineNum($linenum);
                    $sale->serviceID($service);
                    $sale->countryCode('US');
                    $sale->dateBegin($dateBeginStr);
                    $sale->dateEnd($dateEndStr);
                    $sale->productType($productType);
                    $sale->formatType($formatType);
                    $sale->artistName($artistName);
                    $sale->upc($upc);
                    $sale->albumName($albumName) if ( $productType eq RPS::File::Sale::TYPE_ALBUM );
                    $sale->isrc($isrc);
                    $sale->trackName($trackName) if ( $productType eq RPS::File::Sale::TYPE_TRACK );
                    $sale->units($units);
                    $sale->currencyCode('USD');
                    $sale->price($price);
                    $sale->mediaType(RPS::DB::Item::MediaType::kMediaTypeAudio);

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

                }
                next;
            }
        }
    }
    return $linenum;
}

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