# This file is part of k4ever, a point-of-sale system
#   Contact............  <k4ever@lists.someserver.de>
#   Website............  http://k4ever.someserver.de/
#   Bug tracker........  http://k4ever.someserver.de/report
#
# Licensed under GNU Affero General Public License v3 or later

from django import forms
from django.core.exceptions import ValidationError
import re
from decimal import Decimal, InvalidOperation


class CurrencyInput (forms.TextInput):
	def render(self, name, value, attrs=None):
		if value != '':
			try:
				value = u"%.2f" % value
			except TypeError:
				pass
			return super(CurrencyInput, self).render(name, value, attrs)


class CurrencyField (forms.RegexField):
	""" Represents a currency field for django forms... or something. """
	widget = CurrencyInput
	currencyRe = re.compile(r'^(\+|-)?[0-9]{1,5}([,\.][0-9][0-9]?)?$')
	def __init__(self, *args, **kwargs):
		super(CurrencyField, self).__init__(
			self.currencyRe, None, None, *args, **kwargs)
	def to_python(self, value):
		try:
			value = Decimal(value.replace(",", "."))
		except (ValueError, TypeError, InvalidOperation):
			raise ValidationError("Bitte gib eine Zahl ein")
		return value
	def clean(self, value):
		value = super(CurrencyField, self).clean(value)
		return Decimal(value)
