package BookPub::Import::Importer::Copia::Version5;

use strict;

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

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

sub _fieldMap {
    {
        rPriceType             => 'AN',
        rServiceName           => 'BO',
        countryCode            => 'AL',
        dateBegin              => 'O',
        rProductType           => 'AD',
        rIsbn13                => 'U',
        rTitle                 => 'X',
        rAuthor                => 'Y',
        rImprint               => 'AC',
        rUnits                 => 'AH',
        rUnitPrice             => 'AQ',
        rSales                 => 'AF',
        rReturns               => 'AG',
        rListPrice             => 'BQ',
        rListPriceCurrency     => 'AO',
        rPurchasePrice         => 'AM',
        rPurchasePriceCurrency => 'AO',
        rDiscount              => 'AP',
        rRevenue               => 'BC',
        currencyCode           => 'I',
        priceType              => 'BR',
        priceTypeQualifierID   => 'AA',
    };
}

my %taxFieldMap = (
    rTaxAmount  => 72,
    rState      => 16,
    rPostalCode => 20,
);

my %taxData;
my $foundTaxTab = 0;

sub _headerIdentifier { ( rPriceType => 'Price type' ) }

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }

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

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    my $sheetnum = 0;

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $sheetname = $args{sheet_names}->[$sheetnum];
        $sheetnum++;

        # We need to go through the tax tab and store some of that data in a hash
        # so that we can access it while processing the Sales tab.
        if ( $sheetname eq 'Tax Details' ) {

            # Set the flag, so that we know to do all of the extra stuff for files that
            # have this extra tab.
            $foundTaxTab = 1;
            my $linenum     = 0;
            my $foundHeader = 0;
            foreach my $line (@$sheet) {
                $linenum++;

                if ( $line->[0] eq 'Report ID#' ) {
                    $foundHeader = 1;
                    next;
                } elsif ( $foundHeader == 0 ) {
                    next;
                }

                # We've encountered tax tabs that aren't populated correctly.
                # If we notice that, we'll just pretend we never saw the tax tab.
                if ( $line->[ $taxFieldMap{rUnits} ] eq '#REF!' ) {
                    $foundTaxTab = 0;
                    last;
                }

                # Grab the data and store it
                $taxData{$linenum}{rTaxAmount}  = $line->[ $taxFieldMap{rTaxAmount} ];
                $taxData{$linenum}{rState}      = $line->[ $taxFieldMap{rState} ];
                $taxData{$linenum}{rPostalCode} = $line->[ $taxFieldMap{rPostalCode} ];
            }
        }
    }
}

sub priceType {
    my $self = shift;

    my $type = $self->_getByFieldName('priceType');
    $self->fail("Can't determine priceType") unless $type && $type =~ /^\d+$/;

    if ( $type == 1 ) {
        $type = 'rrp';
    } elsif ( $type == 2 ) {
        $type = 'rrpplustax';
    } elsif ( $type == 41 ) {
        $type = 'agency';
    } elsif ( $type == 42 ) {
        $type = 'agencyplustax';
    }

    return $type;
}

sub priceTypeQualifierID {
    my $self = shift;

    my $type       = $self->_getByFieldName('priceTypeQualifierID') || '';
    my $publishers = 'Berrett-Koehler|Macmillan(?: Australia)?|Hachette(?: [a-z]{2})?';
    my $ending     = 'Trade|Higher Ed(?: \(Coresource\))?|-?HE|BFW\(Students\)|DRM \(AU\)';

    if ( $type =~ / K-12$/i ) {
        return BookPub::DB::Item::PriceTypeQualifier::kSchoolLibrary;
    } elsif ( $type =~ /^(?:$publishers)$/i || $type =~ /(?:$publishers)?.*(?:$ending)$/i ) {
        return;
    }

    $self->fail("Unexpected priceTypeQualifier: $type");
}

sub rTaxAmount {
    my $self = shift;
    my $tax  = 0;

    if ( $foundTaxTab == 1 ) {
        $tax = $taxData{ $self->linenum }{rTaxAmount};
    }
    return $tax;
}

sub rState {
    my $self = shift;
    my $state;

    if ( $foundTaxTab == 1 ) {
        $state = $taxData{ $self->linenum }{rState};
    }
    return $state;
}

sub rPostalCode {
    my $self = shift;
    my $postal;

    if ( $foundTaxTab == 1 ) {
        $postal = $taxData{ $self->linenum }{rPostalCode};
    }
    return $postal;
}

sub rProductType {
    my $self = shift;
    my $type = $self->_getByFieldName('rProductType');

    if ( lc($type) eq 'dg' || lc($type) eq 'oo' ) {
        $type = 'ebook';
    }

    return $type;
}

1;
