from oscar.core.loading import get_class, get_classes

from ocyan.core.fender import config
from ocyan.plugin.oscar.fender import get_default_tax_rate
from ocyan.plugin.oscar_partner.partner.utils import round_to_two_dec

ExcludingTaxPriceSelector, IncludingTaxPriceSelector = get_classes(
    "partner.taxbase", ["ExcludingTaxPriceSelector", "IncludingTaxPriceSelector"]
)
tax_rate_as_fraction = get_class("taxes.taxrate", "tax_rate_as_fraction")


USE_PRICE_INCL_TAX = config.get("oscar", "use_price_incl_tax", True)
TAX_RATE = config.get("shipping", "shipping_tax_rate", get_default_tax_rate())
TAX_PERCENTAGE = tax_rate_as_fraction(TAX_RATE)

__all__ = ("taxed_shipping_charge",)


if USE_PRICE_INCL_TAX:

    def taxed_shipping_charge(price, user=None, request=None):
        return IncludingTaxPriceSelector(
            user,
            request,
            currency=price.currency,
            incl_tax=price.incl_tax,
            vat_rate=TAX_RATE,
            is_shipping_charge=True,
        )

else:

    def taxed_shipping_charge(price, user=None, request=None):
        price = ExcludingTaxPriceSelector(
            user,
            request,
            currency=price.currency,
            excl_tax=price.excl_tax,
            vat_rate=TAX_RATE,
            is_shipping_charge=True,
        )
        price.tax = round_to_two_dec(price.tax)
        return price
