package BookPub::Import::Importer::CourseSmart2;

use strict;

use Date::Calc qw(Days_in_Month);
use Data::Dumper;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';

use base 'BookPub::Import::Importer';

sub _fieldMap {
    my $self = shift;
    
    my %fieldMap =
    (
    	11 => {        	
    	    rState                 => 'I',
    	    rPostalCode            => 'J',
            dateBegin              => 'E',
            rIsbn10                => 'M',   
            rIsbn13                => 'N',
            rTitle                 => 'R',                      
            rAuthor                => 'Q',
            rImprint               => 'F',                      
            rUnits                 => 'U', 
            rListPrice             => 'V',
            rCOGS                  => 'AA',                                
            rRevenue               => 'AB',           
            rDuration              => 'T',           
            rInstitution           => 'K',           
            rPurchaseType          => 'G',
            rFee                   => 'X',
            rDeliveryMethod        => 'C',
            rChannel               => 'D',
            rTransactionCategory   => 'Z',
        },                
    );        
    
    return $fieldMap{$self->_version()};
}

sub _headerIdentifier { ( rIsbn13 => qr/ISBN/ ) }

sub _useIsSaleRec  { 1 }
sub _autoParseTitleAndSubtitle { 1 }

sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType     { 'rrp' }
sub currencyCode  { 'USD' }
sub _dateFormat   { ['numerical_year_first', 'iso'] }
sub _useIsSaleRec { 1 }

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName( 'dateBegin' ) || return;

    # the date is being returned in the "days since 1/1/1900" format, so we need
    # to convert it.  We'll check if it's a 5 digit number and greater than the 
    # number of days since 1/1/1900 on 1/1/2006, which is 38716
    if ($date =~ /^\d{5}$/ and $date > 38716) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt("yyyy-mm-dd", $date);
    }
    
    return $date;
}

sub _getDateEnd {
    my $self = shift;
    my $date = $self->_getByFieldName( 'dateEnd' ) || return;

    # the date is being returned in the "days since 1/1/1900" format, so we need
    # to convert it.  We'll check if it's a 5 digit number and greater than the 
    # number of days since 1/1/1900 on 1/1/2006, which is 38716
    if ($date =~ /^\d{5}$/ and $date > 38716) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt("yyyy-mm-dd", $date);       
    }
    
    return $date;
}

sub purchaseType    { 
    my $self = shift;
    my $purchaseType = $self->_getByFieldName( 'rPurchaseType' );
    
    if( $purchaseType ) {
        if (lc($purchaseType) eq 'subscription' || lc($purchaseType) eq '' || lc($purchaseType) eq 'unredeemed') {
            return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
        } else {
            $self->fail( "Unknown purchase type: $purchaseType" )   
        }
    }
}

sub countryCode {
    my $self = shift;
    my $filename = $self->filename;
    
    if ( $filename =~ /US/ && $filename !~ /Canada/ ) { 
        return "US";
    } elsif ( $filename =~ /Canada/ && $filename !~ /US/ ) { 
        return "CA";
    } else {
        $self->fail( "Could not find country code in filename: $filename" );
    }
}

# hash of two-letter Canadian province abbreviations
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,
);  

sub state
{
    my $self = shift;
    my $state;
    if (my $rState = $self->rState())
    {
        my $code = $self->countryCode();
        if ( $code eq "US" ) { 
            my $postal = Common::Postal->new($code);
            if ($postal->getName($rState)) {
                # acceptable state abbreviation
                $state = $rState;
            }
        } elsif ( $code eq "CA" ) { 
            if( $provinces{$rState} ) {
                $state = $rState;
            }
        } else {
            $self->fail( "Invalid country code: $code" );
        }
    }
    return $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;
}

sub rState {
    my $self = shift; 
    my $state = $self->SUPER::rState();  
  
    if( $state eq 'UNKNOWN' ) {
        return;
    }
    return $state;
}

sub rPostalCode {
    my $self = shift; 
    my $code = $self->SUPER::rPostalCode();  
  
    if( $code eq 'UNKNOWN' ) {
        return;
    }
    return $code
}


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