import decimal

from ocyan.core.utils import round_to_four_dec

from .constants import REVERSE_CHARGED_TAX_CODE, WORLDWIDE_TAX_CODE


def exclusive_tax_component(tax_percentage):
    """
    >>> c = exclusive_tax_component(decimal.Decimal('0.21'))
    >>> amount = decimal.Decimal('1.61') * c
    >>> round_to_four_dec(amount)
    Decimal('1.9481')
    """
    return decimal.Decimal(1) + tax_percentage


def inclusive_tax_component(tax_percentage):
    """
    >>> c = inclusive_tax_component(decimal.Decimal('0.21'))
    >>> amount = decimal.Decimal('1.95') * c
    >>> round_to_four_dec(amount)
    Decimal('1.6116')
    """
    return decimal.Decimal(1) / exclusive_tax_component(tax_percentage)


def tax_from_price_incl_tax(price_incl_tax, tax_percentage):
    """
    >>> percentag = decimal.Decimal('0.21')
    >>> price_incl_tax = decimal.Decimal('1.95')
    >>> tax_from_price_incl_tax(price_incl_tax, percentag)
    Decimal('0.3384')
    """
    price_excl_tax = inclusive_tax_component(tax_percentage) * price_incl_tax
    return round_to_four_dec(price_incl_tax - price_excl_tax)


def get_country_specific_tax_code(vat_rate, country_code):
    if vat_rate in [REVERSE_CHARGED_TAX_CODE, WORLDWIDE_TAX_CODE]:
        return vat_rate
    return "%s-%s" % (vat_rate.lower(), country_code.lower())
