package BookPub::Import::Importer::CourseSmart;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

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

sub _fieldMap {
    my $self = shift;
    
    my %fieldMap =
    (
    	8 => {        	
    	    rPostalCode            => 'T',
            dateBegin              => 'R',
            dateEnd                => 'S',   
            rIsbn13                => 'G',
            rTitle                 => 'J',                      
            rAuthor                => 'L',                      
            rUnits                 => 'M', 
            rListPrice             => 'N',                                
            rRevenue               => 'O',           
              
        },      
    	9 => {        	
    	    rState                 => 'V',
    	    rPostalCode            => 'U',
            dateBegin              => 'D',
            dateEnd                => 'D',   
            rProductType           => 'P',
            rIsbn10                => 'J',
            rIsbn13                => 'K',
            rTitle                 => 'N',                      
            rAuthor                => 'O',
            rImprint               => 'B',                      
            rUnits                 => 'X',  
            rListPrice             => 'Y',                               
            rRevenue               => 'Y',           
              
        },              
    );        
    
    return $fieldMap{$self->_version()};
}

sub _useIsSaleRec  { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub purchaseType   { BookPub::DB::Item::Sale::kPurchaseTypeLoan }
sub currencyCode   { 'USD' }
sub countryCode    { 'US' }

sub rRevenue { 
    my $self = shift;
    my $revenue = $self->_getByFieldName( 'rRevenue' );

    $revenue *= .7;
    
    return $revenue;
}

sub productType    { 
    my $self = shift;
    
    if ($self->_getByFieldName( 'rProductType' )) {
        my $productType = $self->_getByFieldName( 'rProductType' );
        if (lc($productType) eq 'etextbook') {
            return BookPub::DB::Item::Sale::kProductTypeEBook;
        } else {
            $self->fail( "Unknown product type: $productType" )   
        }
    }
    
    return BookPub::DB::Item::Sale::kProductTypeEBook;
}

sub priceType {
    my $self = shift;
    my $clientID = Common::RSApp::GetClientID();
    if ($clientID == 346) {
        return 'rrp';
    } else {  
        return 'agency';
    }
}

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 countryCode {
    my $self = shift; 
  
    # Throwing an error if there is not a US state or CA province code in this field.
  
    my %provinces = (
      'alberta'                   => 1,
      'ab'                        => 1,
      'british columbia'          => 1,
      'bc'                        => 1,
      'manitoba'                  => 1,
      'mb'                        => 1,
      'new brunswick'             => 1,
      'nb'                        => 1,
      'newfoundland and labrador' => 1,
      'nl'                        => 1,
      'northwest territories'     => 1,
      'nt'                        => 1,
      'nova scotia'               => 1,
      'ns'                        => 1,
      'nunavit'                   => 1,
      'nu'                        => 1,
      'ontario'                   => 1,
      'on'                        => 1,
      'prince edward island'      => 1,
      'pe'                        => 1,
      'quebec'                    => 1,
      'qc'                        => 1,
      'saskatchewan'              => 1,
      'sk'                        => 1,
      'yukon'                     => 1,
      'yt'                        => 1,
    );  
  
    my $state = $self->SUPER::rState();  
    
    my $postalObject = Common::Postal::US->new();
    my $stateAbbr = $postalObject->getAbbr($state);
    
    if (!$stateAbbr) {
        my $stateName = $postalObject->getName($state);  
        if ($stateName) {
            $stateAbbr = $state;
        }
    }
    
    if ($stateAbbr || $state eq '' || lc($state) eq 'unknown') {  
        return 'US';
    } elsif ($provinces{lc($state)}){
        return 'CA';
    } else {
        $self->fail( "Invalid state: $state" );
    }
}

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

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

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.
                # We've got some Canadian ones in the mix, but no way to distinguish which country the sale is for.
                #$self->fail("Invalid postal code '$rPostalCode'");
            }
        }
    }

    return $postalCode;
}

sub _isSaleRec {
    my $self = shift;

    my $listPrice = uc($self->_getByFieldName( 'rListPrice' ));
    
    # We're going to skip the subtotal line.
    if ($listPrice eq 'TTL') {
        return 0;
    }

    return $self->SUPER::_isSaleRec();;
}


1;
