import store from "@/store";
import { storeActions } from "@/constants/store-actions";
import baseMixin from "@/mixins/base-mixin.js";

export function getDisplayAmountDue(lineItemsObject, includeTax = true) {
    return getAmountDue(lineItemsObject, includeTax).toLocaleString("en-US", {
        style: "currency",
        currency: "USD",
    });
}

export function getAmountDue(lineItemsObject, includeTax = true) {
    let amountDue = 0;
    const order = baseMixin?.methods?.hasSubmittedOrder()
        ? baseMixin?.methods?.getSubmittedOrder()
        : store.getters.order;

    if (lineItemsObject?.glassParts) {
        amountDue += baseMixin.methods.getTotalPriceOfAllLineItemsAndChildParts(
            lineItemsObject.glassParts,
            includeTax
        );
    }

    if (lineItemsObject?.supportingItems) {
        amountDue += baseMixin?.methods?.getTotalPriceOfAllLineItemsAndChildParts(
            lineItemsObject.supportingItems,
            includeTax
        );
    }

    if (store.getters.coverageIsVerified && !order.policy.isNoComp && !order.policy.isItac) {
        amountDue = order.policy.currentDeductible;
    }

    if (lineItemsObject?.vaps) {
        amountDue += baseMixin?.methods?.getTotalPriceOfAllLineItemsAndChildParts(
            lineItemsObject.vaps,
            includeTax
        );
    }

    if (lineItemsObject?.promos) {
        amountDue += baseMixin?.methods?.getTotalPriceOfAllLineItemsAndChildParts(
            lineItemsObject.promos,
            includeTax
        );
    }

    return ((amountDue * 100) / 100).toFixed(2);
}

export function getSubTotal(lineItemsObject) {
    // this is amountDue without sales tax
    return getAmountDue(lineItemsObject, false);
}

export function getSalesTax(lineItemsObject) {
    // this is amountDue minus subTotal
    return (((getAmountDue(lineItemsObject) - getSubTotal(lineItemsObject)) * 100) / 100).toFixed(
        2
    );
}

export async function getPricingByDayPartWithPrice(pageNameToLog) {
    // Get the Pricing By Day Part
    const basePriceByDayPart = await baseMixin.methods.dispatchStoreActionWithLogging(
        storeActions.GET_PRICING_BY_DAY_PART,
        null,
        pageNameToLog,
        false
    );

    if (
        basePriceByDayPart?.data === null ||
        basePriceByDayPart?.data === undefined ||
        basePriceByDayPart?.data === ""
    ) {
        return null;
    }

    // Get the Pricing By Day Base Part price
    const pricingResults = await baseMixin.methods.dispatchStoreActionWithLogging(
        storeActions.PRICE_ORDER_ITEMS_AND_SAVE_SERVER_DATA,
        {
            availableLineItems: [basePriceByDayPart?.data],
        },
        pageNameToLog,
        false
    );

    return pricingResults[0];
}
