package RPS::Import::Starbucks;

use strict;

use Date::Calc qw(Days_in_Month);

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

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';

# map version num to the field order
my %field_map = (

# ['VendorName', 'ArtistName', 'AlbumTitle', 'TrackTitle', 'AlbumUPC', 'AlbumTrackType', 'UnitsSold', 'WholeSalePrice', 'PayAmount', 'GenreName', 'TxnDate', 'ISRC']
    1 => {
        'label'       => 0,
        'artist'      => 1,
        'album'       => 2,
        'track'       => 3,
        'upc'         => 4,
        'productType' => 5,
        'units'       => 6,
        'price'       => 7,
        'isrc'        => 11,
    },

# ['VendorName', 'ArtistName', 'AlbumTitle', 'TrackTitle', 'AlbumUPC', 'AlbumTrackType', 'UnitsSold', 'WholeSalePrice', 'PayAmount', 'GenreName'],
    2 => {
        'label'       => 0,
        'artist'      => 1,
        'album'       => 2,
        'track'       => 3,
        'upc'         => 4,
        'productType' => 5,
        'units'       => 6,
        'price'       => 7,
    },

# ['Date', 'Vendor', 'Artist', 'Album Name', 'Track Name', 'UPC', 'Track Num', 'CD Num', 'ISRC', 'Album or Track', 'Quantity', 'Cost', 'Extended Cost'],
    3 => {
        'label'       => 1,
        'artist'      => 2,
        'album'       => 3,
        'track'       => 4,
        'upc'         => 5,
        'trackNum'    => 6,
        'isrc'        => 8,
        'productType' => 9,
        'units'       => 10,
        'price'       => 11,
    },

# ['Vendor Name', 'Artist Name', 'Album Title', 'Track Title', 'Album UPC', 'Album Track Type', 'Units Sold', 'Whole Sale Price', 'Pay Amount', 'Genre Name', 'Txn Date', 'ISRC'] -- tab 0
    4 => {
        'label'       => 0,
        'artist'      => 1,
        'album'       => 2,
        'track'       => 3,
        'upc'         => 4,
        'productType' => 5,
        'units'       => 6,
        'price'       => 7,
        'isrc'        => 11,
    },

# ['VendorName', 'ArtistName', 'AlbumTitle', 'TrackTitle', 'AlbumUPC', 'AlbumTrackType', 'UnitsSold', 'WholeSalePrice', 'PayAmount', 'GenreName', 'TxnDate', 'ISRC'] -- tab 0
    5 => {
        'label'       => 0,
        'artist'      => 1,
        'album'       => 2,
        'track'       => 3,
        'upc'         => 4,
        'productType' => 5,
        'units'       => 6,
        'price'       => 7,
        'isrc'        => 11,
    },

# ['VendorName', 'ArtistName', 'AlbumTitle', 'Track     Title', 'Album   UPC', 'AlbumTrackType', 'UnitsSold', 'WholeSalePrice', 'PayAmount', 'GenreName', 'TxnDate']
    6 => {
        'label'       => 0,
        'artist'      => 1,
        'album'       => 2,
        'track'       => 3,
        'upc'         => 4,
        'productType' => 5,
        'units'       => 6,
        'price'       => 7,
    },
);

#public methods

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

    my $retval  = undef;
    my $sheets  = $args{sheets};
    my $fileObj = $args{file};
    my $version = $fileObj->VersionNum;

    unless ( scalar @$sheets > 1 ) {
        $self->errstr("missing sheets");
        return 0;
    }

    my ( $summary_sheet, $lines );
    if ( $args{sheet_names}->[0] =~ /billing.info/i ) {
        $summary_sheet = $sheets->[0];
        $lines         = $sheets->[1];
    } elsif ( $args{sheet_names}->[1] =~ /billing.info/i ) {
        $summary_sheet = $sheets->[1];
        $lines         = $sheets->[0];
    } else {
        $self->errstr("unknown sheet names");
        print STDERR 'sheet names: ', join( ',', @{ $args{sheet_names} } ), "\n";
        return 0;
    }

    my ( $dateBegin, $dateEnd ) = $self->_getDates($summary_sheet);
    unless ( $dateBegin && $dateEnd ) {
        $self->errstr("couldn't get dates");
        return undef;
    }

    my $offsets;
    if ( $version && exists $field_map{$version} ) {
        $offsets = $field_map{$version};
    } else {
        $self->errstr("wrong version");
        print STDERR "unknown version: $version\n";
        return 0;
    }

    my $format  = RPS::File::Sale::FORMAT_DOWNLOAD;
    my $linenum = 1;
    foreach my $line (@$lines) {
        my $prodtype;
        if ( $line->[ $offsets->{'productType'} ] eq 'A' ) {
            $prodtype = RPS::File::Sale::TYPE_ALBUM;
        } elsif ( $line->[ $offsets->{'productType'} ] eq 'T' ) {
            $prodtype = RPS::File::Sale::TYPE_TRACK;
        }

        my $upc  = exists $offsets->{upc}  ? normalize_upc( $line->[ $offsets->{upc} ] )   : '';
        my $isrc = exists $offsets->{isrc} ? 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'} ] =~ m/^(-?\d+)$/;
        my ($price) = $line->[ $offsets->{'price'} ] =~ m/^(\d*\.?\d*)$/;

        if ( $prodtype && $units && $price && $artist && ( $album || $track ) ) {
            my $sale = RPS::Import::SaleRec->new();

            if ( $version == 3 ) {
                $sale->trackNum( $line->[ $offsets->{'trackNum'} ] );
            }

            $sale->productType($prodtype);
            $sale->formatType($format);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->upc($upc);
            $sale->isrc($isrc);
            $sale->artistName($artist);
            $sale->albumName($album);
            $sale->trackName($track);
            $sale->labelName($label);
            $sale->units($units);
            $sale->price($price);
            $sale->lineNum($linenum);
            $sale->countryCode('US');

            $self->_insertSale( sale => $sale );
        }
        $linenum++;
    }
    return $linenum;
}

#
# Private methods
#

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

    my $dateBegin;
    my $dateEnd;

    foreach my $line (@$lines) {
        my $label = $line->[0];
        my $data  = $line->[1];

        # my $date = Common::Util::normalize_date($line->[FIELD_DATE]);

        if ( $label =~ /reference/i && $data =~ m|(\d?\d/\d?\d/(20)?\d\d) *- *(\d?\d/\d?\d/(20)?\d\d)| ) {
            $dateBegin = normalize_date($1);
            $dateEnd   = normalize_date($3);
            last;
        }
    }

    return ( $dateBegin, $dateEnd );
}

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