# coding: utf-8
import decimal

from babel import Locale
from babel.numbers import parse_pattern
from django.conf import settings
from django.utils.translation import get_language, gettext as _


def format_price(number):
    locale = Locale.parse(get_language() or settings.LANGUAGE_CODE)
    fmt = locale.decimal_formats.get(None)
    pattern = parse_pattern(fmt)

    if '.' in str(number):
        # Non-zero fractional part, enforce trailing zeroes
        frac = (2, 2)
    else:
        frac = (0, 2)

    return pattern.apply(number, locale, force_frac=frac)


def money(value, ndigits=4):
    places = decimal.Decimal('0.%s1' % ('0' * (ndigits - 1)))

    try:
        amount = decimal.Decimal(value).quantize(places)
    except (TypeError, decimal.DecimalException):
        raise ValueError(_('MONETARY::INVALID_VALUE'))

    if amount < 0:
        raise ValueError(_('MONETARY::NEGATIVE_NOT_ALLOWED'))

    return amount


def decimal_round(value):
    return value.quantize(decimal.Decimal('1.'), decimal.ROUND_HALF_UP)
