package BookPub::Import::Importer::Dragonmount::Version1;

use strict;
use Date::Calc qw(Add_Delta_Days);

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

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

sub _fieldMap {
    {
        countryCode => 'I',
        rState      => 'I',
        rPostalCode => 'G',
        dateBegin   => 'B',
        rIsbn13     => 'C',
        rTitle      => 'D',
        rAuthor     => 'F',
        rListPrice  => 'J',
        rRevenue    => 'K',
    };
}

sub _headerIdentifier { ( rTitle => 'title' ) }
sub purchaseType      { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType       { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType         { 'agency' }
sub currencyCode      { 'USD' }
sub units             { 1 }

sub rTitle {
    my $self = shift;

    my $title  = $self->SUPER::rTitle();
    my $author = $self->SUPER::rAuthor();

    if ( $title =~ m/^(.*) by $author$/ ) {
        $title = $1;
    }
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $title;
}

sub rSubtitle {
    my $self = shift;

    my $title  = $self->SUPER::rTitle();
    my $author = $self->SUPER::rAuthor();

    if ( $title =~ m/^(.*) by $author$/ ) {
        $title = $1;
    }
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $subtitle;
}

sub countryCode {
    my $self = shift;

    # Throwing an error if there is not a US state or CA province code in this field.
    #

    my %provinces = (
        ab => 1,
        bc => 1,
        mb => 1,
        nb => 1,
        nl => 1,
        nt => 1,
        ns => 1,
        nu => 1,
        on => 1,
        pe => 1,
        qc => 1,
        sk => 1,
        yt => 1,
    );

    my $state = lc( $self->SUPER::rState() || '' );
    $self->fail("Missing state") unless ($state);

    my $postalObject = Common::Postal::US->new();
    my $stateName    = $state =~ /^[a-z]{2}$/i ? $postalObject->getName($state) : $state;
    if ($stateName) {
        return 'US';
    } elsif ( exists $provinces{$state} ) {
        return 'CA';
    } else {
        $self->fail("Invalid state: $state");
    }
}

sub postalCode {
    my $self = shift;

    my $postalCode;

    if ( my $rPostalCode = $self->rPostalCode() ) {
        if ( $rPostalCode =~ /^(\d{5})-$/ ) {
            $rPostalCode = $1;
        }

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

            if ( !$postalCode ) {
                return;

                # Rather than throwing an error, we'll just leave out the invalid zip codes.
                #$self->fail("Invalid postal code '$rPostalCode'");
            }
        }
    }

    return $postalCode;
}

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