package BookPub::Import::Importer::SimplyAudio;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Date::Calc qw(Days_in_Month);

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

sub _fieldMap {
    {
        dateBegin    => 'A',
        rTitle       => 'C',
        rIsbn13      => 'B',
    };
}

sub _unverifiedFieldMap {
    {
        clubDownloads     => 'D',
        alaCarteDownloads => 'H',
        clubListPrice     => 'E',
        alaCarteListPrice => 'I',
        clubDiscount      => 'F',
        alaCarteDiscount  => 'J',
        clubRevenue       => 'G',
        alaCarteRevenue   => 'K',
        _dateBeginMonthlyReport => 'A13',
    };
}

sub _headerIdentifier { rIsbn13 => 'ISBN' }

my %months = (
    jan => 1,
    feb => 2,
    mar => 3,
    apr => 4,
    may => 5,
    jun => 6,
    jul => 7,
    aug => 8,
    sep => 9,
    oct => 10,
    nov => 11,
    dec => 12,
);

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }

sub priceType          { 'rrp' }
sub countryCode        { 'US' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub productType        { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub rProductType       { BookPub::DB::Item::Sale::kProductTypeAudioBook }

sub rServiceName {
    return BookPub::Tracker::Service::GetDefaultServiceName( service_id => shift->serviceID );
}

sub _getDateBegin {
    my $self = shift;
    return $self->{_date_begin} if $self->{_date_begin};
    return sprintf "%04d-%02d-%02d", $self->{_year}, $self->{_month}, 1;
}

sub _getDateEnd {
    my $self = shift;
    return $self->{_date_end} if $self->{_date_end};
    return sprintf "%04d-%02d-%02d", $self->{_year}, $self->{_month}, Days_in_Month( $self->{_year}, $self->{_month} );
}

sub _processHeader {
    my ($self, %args) = @_;

    # 'Monthly
    if ( $self->sheetname =~ /^Monthly Report$/i ) {
        my $dateRange = $self->_getByFieldName('_dateBeginMonthlyReport') || '';
        if ( $dateRange =~ /(\d{1,2})[.\/-_](\d{1,2})[.\/-_](?:20)?(\d{2})\s+-\s+(\d{1,2})[.\/-_](\d{1,2})[.\/-_](?:20)?(\d{2})/ ) {
            $self->{_date_begin} = sprintf "20%02d-%02d-%02d", $3, $1, $2;
            $self->{_date_end}   = sprintf "20%02d-%02d-%02d", $6, $4, $5;
            $self->{_monthly_report} = 1;
            return 1;
        }
        $self->fail("Could not determine sale period from: '$dateRange'.");
    }
    # Quarterly
    elsif ( $self->sheetname =~ /^Title Data$/i && !$self->{_monthly_report} ) {
        $self->_getDateYear();
        $self->_getDateMonth();
    }

    return 1;
}

sub _getDateYear {
    my $self = shift;

    unless ( $self->{_year} ) {
        ( $self->{_year} ) = $self->filename =~ /^(\d{4}) /;
        $self->fail("Could not determine year from file name") unless $self->{_year};
    }

    return $self->{_year};
}

sub _getDateMonth {
    my $self = shift;

    my $month = substr( lc( $self->_getByFieldName('dateBegin') || '' ), 0, 3);
    if ( exists $months{$month} ) {
        $self->{_month} = sprintf "%2d", $months{$month};
    }

    return 1;
}

sub _isClubDownloads {
    my $self = shift;

    if ( $self->_clubDownloads && !$self->_alaCarteDownloads ) {
        return 1;
    } elsif ( !$self->_clubDownloads && $self->_alaCarteDownloads ) {
        return 0;
    }

    $self->fail("There are no units.");
}

sub purchaseType {
    my $self = shift;

    return $self->_isClubDownloads
        ? BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL
        : BookPub::DB::Item::Sale::kPurchaseTypeDownload;
}

sub rUnits {
    my $self = shift;

    my $clubDownloads     = $self->_getByFieldName('clubDownloads')     || 0;
    my $alaCarteDownloads = $self->_getByFieldName('alaCarteDownloads') || 0;

    return $self->_isClubDownloads ? $clubDownloads : $alaCarteDownloads;
}

sub rListPrice {
    my $self = shift;

    my $clubListPrice     = $self->_getByFieldName('clubListPrice')     || 0;
    my $alaCarteListPrice = $self->_getByFieldName('alaCarteListPrice') || 0;

    return $self->_isClubDownloads ? $clubListPrice : $alaCarteListPrice;
}

sub rCOGS {
    my $self = shift;

    my $clubDiscount     = $self->_getByFieldName('clubDiscount')     || 0;
    my $alaCarteDiscount = $self->_getByFieldName('alaCarteDiscount') || 0;

    my $value = $self->_isClubDownloads ? $clubDiscount : $alaCarteDiscount;
    $value =~ s/%//g;

    return $value > 1 ? $value * 0.01 : $value;
}

sub rRevenue {
    my $self = shift;

    my $clubRevenue     = $self->_getByFieldName('clubRevenue')     || 0;
    my $alaCarteRevenue = $self->_getByFieldName('alaCarteRevenue') || 0;

    return $self->_isClubDownloads ? $clubRevenue : $alaCarteRevenue;
}

sub _isSaleRec {
    my $self = shift;

    my $isbn = $self->_getByFieldName('rIsbn13') || '';
    if ( $isbn =~ /^ISBN$/i ) {
        $self->_getDateMonth();
        return;
    }

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

sub _saveLine {
    my $self = shift;

    my $clubDownloads     = $self->{_club_downloads}     = $self->_getByFieldName('clubDownloads')     || 0;
    my $alaCarteDownloads = $self->{_alacarte_downloads} = $self->_getByFieldName('alaCarteDownloads') || 0;
    if ( $clubDownloads && $alaCarteDownloads ) {
        # reset _alacarte_downloads to create the first record for a line
        $self->{_club_downloads}     = $clubDownloads;
        $self->{_alacarte_downloads} = 0;
        $self->SUPER::_saveLine();

        # reset club_downloads to create the second record for a line
        $self->{_club_downloads}     = 0;
        $self->{_alacarte_downloads} = $alaCarteDownloads;
    }

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

sub _clubDownloads {
    return $_[0]->{_club_downloads};
}

sub _alaCarteDownloads {
    return $_[0]->{_alacarte_downloads};
}

1;
