package BookPub::Import::Importer::DNAML::Version3;

use strict;

use lib '/app/tools/common/lib';
use Common::Postal;

use lib '/app/tools/bookpub/lib';
use base 'BookPub::Import::Importer::DNAML::Base';

sub _fieldMap {
    {
        rSubtitle    => '1',
        dateBegin    => '2',
        rDiscount    => '4',
        countryCode  => '11',
        rTitle       => '16',
        rIsbn13      => '17',
        rListPrice   => '18',
        currencyCode => '19',
        rState       => '20',
        rPostalCode  => '22',
    };
}

sub _headerIdentifier { ( rSubtitle => 'eBook Title' ) }

sub priceType { 'agency' }

sub _importLines {
    my $self = shift;
    my %args = @_;
    my $lines;
    $self->{lines} = $args{lines};

    my $sheetNumber = 0;
    my $saleCount   = 0;

    foreach my $sheet ( @{ $args{sheets} } ) {
        $self->{sheetnum} = $sheetNumber;
        $lines = $args{sheets}[$sheetNumber];

        if ( $args{sheet_names}->[$sheetNumber] =~ /Sheet1/i ) {
            Log->info("Sheet: $args{sheet_names}->[$sheetNumber]");
            foreach my $line (@$lines) {
                $self->{line} = $line;
                $self->_processHeader($sheet);
            }
        }
        if ( $args{sheet_names}->[$sheetNumber] =~ /Data/i ) {
            Log->info("Sheet: $args{sheet_names}->[$sheetNumber]");
            for ( my $i = 0 ; $i < scalar @$lines ; $i++ ) {
                my $line = $lines->[$i];

                my $title   = $line->[ $self->_fieldMap->{rTitle} ];
                my $rIsbn13 = $line->[ $self->_fieldMap->{rIsbn13} ];
                my $isbn13  = $line->[ $self->_fieldMap->{rIsbn13} ];
                $isbn13 =~ s/^isbn\s+//i;
                my $rListPrice   = $line->[ $self->_fieldMap->{rListPrice} ];
                my $listPrice    = $rListPrice / 100;
                my $currencyCode = $line->[ $self->_fieldMap->{currencyCode} ];
                my $countryCode  = $line->[ $self->_fieldMap->{countryCode} ];
                $self->{_countryCode} = $countryCode;
                my $rState = $line->[ $self->_fieldMap->{rState} ];
                $self->{_rState} = $rState;
                my $rPostalCode = $line->[ $self->_fieldMap->{rPostalCode} ];
                $self->{_rPostalCode} = $rPostalCode;
                my $state        = $self->state();
                my $postalCode   = $self->postalCode();
                my $discount     = $self->{_discount};
                my $revenue      = $listPrice * $discount;
                my $units        = 1;
                my $productType  = $self->productType();
                my $purchaseType = $self->purchaseType();
                my $formatType   = $self->formatType();

                if ( ( $title || $isbn13 ) && $units ) {

                    my $saleRec = BookPub::Import::SaleRec->new();

                    $saleRec->productType($productType);
                    $saleRec->formatType($formatType);
                    $saleRec->purchaseType($purchaseType);
                    $saleRec->currencyCode($currencyCode);
                    $saleRec->countryCode($countryCode);
                    $saleRec->rState($rState);
                    $saleRec->rPostalCode($rPostalCode);
                    $saleRec->state($state);
                    $saleRec->postalCode($postalCode);
                    $saleRec->lineNum( $i + 1 );
                    $saleRec->dateBegin( $self->dateBegin() );
                    $saleRec->dateEnd( $self->dateEnd() );
                    $saleRec->listPrice($listPrice);
                    $saleRec->units($units);
                    $saleRec->revenue($revenue);
                    $saleRec->isAgency('Y');
                    $saleRec->rTitle($title);
                    $saleRec->units($units);
                    $saleRec->rListPrice($rListPrice);
                    $saleRec->listPrice($listPrice);
                    $saleRec->discount($discount);
                    $saleRec->revenue($revenue);
                    $saleRec->rIsbn13($isbn13);

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

                    Log->info("Title: $title");
                    Log->info("Isbn13: $isbn13");
                    Log->info("listPrice: $listPrice");
                    Log->info("units: $units");
                    Log->info("currencyCode: $currencyCode");
                    Log->info("countryCode: $countryCode");
                    Log->info("state: $state");
                    Log->info("postalCode: $postalCode");
                    Log->info("discount: $discount");
                    Log->info("revenue: $revenue");
                    Log->info("dateBegin: $self->{_dateBegin}");
                    Log->info("dateEnd: $self->{_dateEnd}");
                    Log->info("productType: $productType");
                    Log->info("purchaseType: $purchaseType");
                    Log->info("formatType: $formatType");
                    my $num = $i + 1;
                    Log->info("lineNumber: $num");
                    Log->info("-----");

                    $saleCount++;
                }
            }
        }
        $sheetNumber++;
    }
    return $saleCount;
}

sub _processHeader {
    my $self = shift;

    $self->_storeDates();

    if ( $self->_isHeader() ) {
        $self->_storeDiscount();
        $self->_validateHeaderData();
    }

}

sub _validateHeaderData {
    my $self = shift;

    # Do we want to do data validation for the header?

    die "Could not determine start and end date" unless ( $self->dateBegin );
    die "Could not determine discount rate"      unless ( $self->rDiscount );
}

sub state {
    my $self = shift;

    my $state;

    if ( my $rState = $self->{_rState} ) {
        if ( my $postal = Common::Postal->new( $self->{_countryCode} ) ) {
            if ( $postal->getName($rState) ) {

                # acceptable state abbreviation
                $state = $rState;
            } else {

                # look up by the full state name
                $state = $postal->getAbbr($rState);
            }

            if ( !$state ) {

                # Apple seems to run with PI right now, an
                # obsolete code for Philippine Islands.
                # We'll let that slide (but we won't normalize
                # with it either).

                if ( uc($rState) ne 'PI' ) {
                    $self->fail( "Invalid state '$rState' (country: " . $self->{_countryCode} . ")" );
                }
            }
        }
    }

    return $state;
}

sub postalCode {
    my $self = shift;

    my $postalCode;

    if ( my $rPostalCode = $self->{_rPostalCode} ) {
        if ( my $postal = Common::Postal->new( $self->{_countryCode} ) ) {
            $postalCode = $postal->formatPostalCode($rPostalCode);

            if ( !$postalCode ) {
                $self->fail("Invalid postal code '$rPostalCode'");
            }
        }
    }

    return $postalCode;
}

1;
