from django.conf import settings
from django.utils.translation import gettext, gettext_lazy

from oscar.core.loading import get_class

from ocyan.core.fender import config

from ocyan.plugin.oscar.constants import (
    TAX_RATE_HIGH,
    TAX_RATE_LOW,
    TAX_RATE_ZERO,
)
from ocyan.plugin.oscar.taxes.constants import (
    REVERSE_CHARGED_TAX_CODE,
    WORLDWIDE_TAX_CODE,
)

COUNTRY_TAX_RATES = get_class("taxes.constants", "COUNTRY_TAX_RATES")


class InvalidTaxRateException(Exception):
    pass


ALL_TAX_RATES = (
    (TAX_RATE_ZERO, gettext_lazy(TAX_RATE_ZERO)),
    (TAX_RATE_LOW, gettext_lazy(TAX_RATE_LOW)),
    (TAX_RATE_HIGH, gettext_lazy(TAX_RATE_HIGH)),
)


def get_supported_tax_rate_choices():
    return [(key, gettext(key)) for key in get_supported_tax_rates()]


def get_supported_tax_rates():
    tax_rates = config.get("oscar", "tax_rates")
    if not tax_rates:
        return [TAX_RATE_HIGH]
    return tax_rates


def get_default_tax_rate():
    tax_rates = get_supported_tax_rates()
    if TAX_RATE_HIGH in tax_rates:
        return TAX_RATE_HIGH
    elif TAX_RATE_LOW in tax_rates:
        return TAX_RATE_LOW

    return tax_rates[0]


def tax_rate_as_fraction(rate, country=settings.OSCAR_VAT_COUNTRY_OF_ORIGIN_CODE):
    if rate in [REVERSE_CHARGED_TAX_CODE, WORLDWIDE_TAX_CODE]:
        return 0

    try:
        return COUNTRY_TAX_RATES[country][rate]
    except KeyError as e:
        raise InvalidTaxRateException(
            "%s is not a valid tax rate for %s" % (rate, country)
        ) from e
