package RPS::Import::Zingy;

use strict;

use Date::Calc qw(Days_in_Month);
use Spreadsheet::ParseExcel;

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

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

my %fieldMap = (

    # 'Territory' 'Qrt' 'Year' 'kind' 'itemID' 'Title' 'Artist' 'Koch Share' 'Pricing' 'Dobson' 'Nextel' 'Zingy AT&T' 'Boost' 'TOTAL' '$'
    'tableA' => {
        'territory'  => 0,
        'quarter'    => 1,
        'year'       => 2,
        'title'      => 5,
        'artist'     => 6,
        'units'      => 13,
        'totalPrice' => 14,
    },

    # 'Territory' 'Qrt' 'Year' 'kind' 'itemID' 'Title' 'Artist' 'Koch Share' 'Pricing' 'Zingy BREW' '$'
    'tableB' => {
        'territory'  => 0,
        'quarter'    => 1,
        'year'       => 2,
        'title'      => 5,
        'artist'     => 6,
        'units'      => 9,
        'totalPrice' => 10,
    },

);

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

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

    my $retval = undef;
    my $lines  = $args{lines};

    if ($lines) {
        my $dateBegin;
        my $dateEnd;

        ( $dateBegin, $dateEnd ) = _getDates($lines);

        unless ( $dateBegin && $dateEnd ) {
            $self->errstr("couldn't get dates");
            return 0;
        }

        my $offset;
        my $linenum = 1;
        foreach my $line (@$lines) {

            # there are two table with data in these files and they
            # each have a different number of columns, so we need
            # to know which table we're dealing with.
            #
            # so look for a table heading, first column="Territory".
            if ( $line->[0] =~ /^Territory$/i ) {
                my $setNewFieldMap = 0;
                foreach my $key ( keys %fieldMap ) {
                    my $href = $fieldMap{$key};

                    my $maxCol = $#$line;

                    # see if the columns are where we expect them to be
                    if (   $maxCol >= $href->{'units'}
                        && $maxCol >= $href->{'totalPrice'}
                        && $line->[ $href->{'totalPrice'} ] eq '$' ) {
                        $offset         = $href;
                        $setNewFieldMap = 1;
                        last;
                    }
                }
                next if ($setNewFieldMap);
            }
            if ( !$offset ) {

                # keep looking until we've found a table
                # of data that we recognize.
                next;
            }

            my $artist      = $line->[ $offset->{'artist'} ];
            my $track       = $line->[ $offset->{'title'} ];
            my $units       = $line->[ $offset->{'units'} ];
            my $total_price = $line->[ $offset->{'totalPrice'} ];
            my $price       = $total_price / $units if ( $units > 0 );

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

                $sale->productType(RPS::File::Sale::TYPE_TRACK);
                $sale->formatType(RPS::File::Sale::FORMAT_RINGTONE);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->artistName($artist);
                $sale->trackName($track);
                $sale->units($units);
                $sale->price($price);
                $sale->lineNum($linenum);

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

    return $retval;
}

#
# Private methods
#

sub _getDates {
    my $lines = shift;
    my ( $beginDate, $endDate );

    foreach my $line (@$lines) {
        last if ( $beginDate && $endDate );

        my $qtr  = $line->[ $fieldMap{'tableA'}->{'quarter'} ];
        my $year = $line->[ $fieldMap{'tableA'}->{'year'} ];

        if ( $qtr =~ /Q(\d)/i && $year ) {
            $qtr = $1;

            my $startMonth = 1 + ( $qtr - 1 ) * 3;
            my $endMonth = $startMonth + 2;

            $beginDate = Common::Util::normalize_date( join( '-', $startMonth, "1", $year ) );
            if ($beginDate) {
                my $lastDay = Days_in_Month( $year, $endMonth );
                $endDate = Common::Util::normalize_date( join '-', $endMonth, $lastDay, $year );
            }
        }
    }

    return ( $beginDate, $endDate );
}

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