from collections import OrderedDict

from .base import ApiBase
import logging

logger = logging.getLogger(__name__)


class Invoices(ApiBase):
    SIMPLE_FIELDS = [
        'accountingBookDetailList',
        'altHandlingCost',
        'altShippingCost',
        'amountPaid',
        'amountRemaining',
        'balance',
        'billingAddress',
        'canHaveStackable',
        'contribPct',
        'createdDate',
        'currencyName',
        'customFieldList',
        'deferredRevenue',
        'discountAmount',
        'discountDate',
        'discountRate',
        'discountTotal',
        'dueDate',
        'email',
        'endDate',
        'estGrossProfit',
        'estGrossProfitPercent',
        'exchangeRate',
        'excludeCommission',
        'expCostDiscAmount',
        'expCostDiscPrint',
        'expCostDiscRate',
        'expCostDiscTax1Amt',
        'expCostDiscTaxable',
        'expCostList',
        'expCostTaxRate1',
        'expCostTaxRate2',
        'externalId',
        'fax',
        'fob',
        'giftCertApplied',
        'giftCertRedemptionList',
        'handlingCost',
        'handlingTax1Rate',
        'handlingTax2Rate',
        'internalId',
        'isTaxable',
        'itemCostDiscAmount',
        'itemCostDiscPrint',
        'itemCostDiscRate',
        'itemCostDiscTax1Amt',
        'itemCostDiscTaxable',
        'itemCostList',
        'itemCostTaxRate1',
        'itemCostTaxRate2',
        'itemList',
        'lastModifiedDate',
        'linkedTrackingNumbers',
        'memo',
        'message',
        'onCreditHold',
        'otherRefNum',
        'partnersList',
        'promotionsList',
        'recognizedRevenue',
        'recurringBill',
        'revRecEndDate',
        'revRecOnRevCommitment',
        'revRecStartDate',
        'revenueStatus',
        'salesEffectiveDate',
        'salesTeamList',
        'shipDate',
        'shipGroupList',
        'shipIsResidential',
        'shippingAddress',
        'shippingCost',
        'shippingTax1Rate',
        'shippingTax2Rate',
        'source',
        'startDate',
        'status',
        'subTotal',
        'syncPartnerTeams',
        'syncSalesTeams',
        'tax2Total',
        'taxDetailsList',
        'taxDetailsOverride',
        'taxPointDate',
        'taxRate',
        'taxRegOverride',
        'taxTotal',
        'timeDiscAmount',
        'timeDiscPrint',
        'timeDiscRate',
        'timeDiscTax1Amt',
        'timeDiscTaxable',
        'timeList',
        'timeTaxRate1',
        'timeTaxRate2',
        'toBeEmailed',
        'toBeFaxed',
        'toBePrinted',
        'total',
        'totalCostEstimate',
        'trackingNumbers',
        'tranDate',
        'tranId',
        'tranIsVsoeBundle',
        'vatRegNum',
        'vsoeAutoCalc',
        'nullFieldList',
    ]

    RECORD_REF_FIELDS = [
        'account',
        'approvalStatus',
        'billAddressList',
        'billingAccount',
        'billingSchedule',
        'class',
        'createdFrom',
        'currency',
        'customForm',
        'department',
        'discountItem',
        'entityTaxRegNum',
        'expCostDiscount',
        'expCostTaxCode',
        'handlingTaxCode',
        'itemCostDiscount',
        'itemCostTaxCode',
        'job',
        'leadSource',
        'location',
        'messageSel',
        'nextApprover',
        'nexus',
        'opportunity',
        'partner',
        'postingPeriod',
        'promoCode',
        'revRecSchedule',
        'salesGroup',
        'salesRep',
        'shipAddressList',
        'shipMethod',
        'shippingTaxCode',
        'subsidiary',
        'subsidiaryTaxRegNum',
        'taxItem',
        'terms',
        'timeDiscount',
        'timeTaxCode',
    ]

    def __init__(self, ns_client):
        ApiBase.__init__(self, ns_client=ns_client, type_name='Invoice')

    def post(self, data) -> OrderedDict:
        assert data['externalId'], 'missing external id'
        invoice = self.ns_client.Invoice(**data)

        invoice['entity'] = self.ns_client.RecordRef(**(data['entity']))

        self.build_simple_fields(self.SIMPLE_FIELDS, data, invoice)

        self.build_record_ref_fields(self.RECORD_REF_FIELDS, data, invoice)

        logger.debug('able to create invoice = %s', invoice)

        res = self.ns_client.upsert(invoice)
        return self._serialize(res)
