""" Custom fields used in InvenTree """

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from .validators import allowable_url_schemes

from django.utils.translation import ugettext_lazy as _

from django.forms.fields import URLField as FormURLField
from django.db import models as models
from django.core import validators
from django import forms

from decimal import Decimal
from djmoney.models.fields import MoneyField as ModelMoneyField
from djmoney.forms.fields import MoneyField

import InvenTree.helpers
from common.settings import currency_code_default


class InvenTreeURLFormField(FormURLField):
    """ Custom URL form field with custom scheme validators """

    default_validators = [validators.URLValidator(schemes=allowable_url_schemes())]


class InvenTreeURLField(models.URLField):
    """ Custom URL field which has custom scheme validators """

    default_validators = [validators.URLValidator(schemes=allowable_url_schemes())]

    def formfield(self, **kwargs):
        return super().formfield(**{
            'form_class': InvenTreeURLFormField
        })


class InvenTreeModelMoneyField(ModelMoneyField):
    def __init__(self, **kwargs):
        default_currency = currency_code_default

        # remove from kwargs if set
        if 'default_currency' in kwargs:
            default_currency = kwargs['default_currency']
            kwargs.pop('default_currency')

        super().__init__(default_currency=default_currency, **kwargs)
    pass


class InvenTreeMoneyField(MoneyField):
    pass


class DatePickerFormField(forms.DateField):
    """
    Custom date-picker field
    """

    def __init__(self, **kwargs):

        help_text = kwargs.get('help_text', _('Enter date'))
        label = kwargs.get('label', None)
        required = kwargs.get('required', False)
        initial = kwargs.get('initial', None)

        widget = forms.DateInput(
            attrs={
                'type': 'date',
            }
        )

        forms.DateField.__init__(
            self,
            required=required,
            initial=initial,
            help_text=help_text,
            widget=widget,
            label=label
        )


def round_decimal(value, places):
    """
    Round value to the specified number of places.
    """

    if value is not None:
        # see https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize for options
        return value.quantize(Decimal(10) ** -places)
    return value


class RoundingDecimalFormField(forms.DecimalField):
    def to_python(self, value):
        value = super(RoundingDecimalFormField, self).to_python(value)
        value = round_decimal(value, self.decimal_places)
        return value

    def prepare_value(self, value):
        """
        Override the 'prepare_value' method, to remove trailing zeros when displaying.
        Why? It looks nice!
        """

        if type(value) == Decimal:
            return InvenTree.helpers.normalize(value)
        else:
            return value


class RoundingDecimalField(models.DecimalField):
    def to_python(self, value):
        value = super(RoundingDecimalField, self).to_python(value)
        return round_decimal(value, self.decimal_places)

    def formfield(self, **kwargs):
        defaults = {
            'form_class': RoundingDecimalFormField
        }

        defaults.update(kwargs)

        return super().formfield(**kwargs)

@@ -358,16 +358,49 @@
 rt forms
+%0Afrom django.conf import settings
 %0A%0Afrom d
@@ -555,20 +555,22 @@
 helpers%0A
-from
+import
  common.
@@ -581,37 +581,8 @@
 ings
- import currency_code_default
 %0A%0A%0Ac
@@ -1156,46 +1156,205 @@
     
-def __init__(self, **kwargs):%0A        
+%22%22%22 custom MoneyField for clean migrations while havoing dynamic currency settings %22%22%22%0A    def __init__(self, **kwargs):%0A        # remove currency information for a clean migration%0A        kwargs%5B'
 defa
@@ -1369,109 +1369,449 @@
 ency
+'%5D
  = 
-currency_code_default%0A%0A        # remove from kwargs if set%0A        if 'default_currency' in 
+''%0A        kwargs%5B'currency_choices'%5D = %5B%5D%0A%0A        super().__init__(**kwargs)%0A%0A    def formfield(self, **kwargs):%0A        %22%22%22 override form class to use own function %22%22%22%0A        kwargs%5B'form_class'%5D = InvenTreeMoneyField%0A        return super().formfield(**kwargs)%0A%0A%0Aclass InvenTreeMoneyField(MoneyField):%0A    %22%22%22 custom MoneyField for clean migrations while havoing dynamic currency settings %22%22%22%0A    def __init__(self, *args, **
 kwargs
+)
 :%0A  
@@ -1820,62 +1820,142 @@
     
-    default_currency = kwargs%5B'default_currency'%5D%0A    
+# override initial values with the real info from database%0A        kwargs%5B'currency_choices'%5D = %5B(a, a) for a in settings.CURRENCIES%5D%0A
     
@@ -1968,13 +1968,9 @@
 args
-.pop(
+%5B
 'def
@@ -1987,139 +1987,91 @@
 ncy'
-)%0A%0A        super().__init__(default_currency=default_currency, **kwargs)%0A    pass%0A%0A%0Aclass InvenTreeMoneyField(MoneyField):%0A    pass
+%5D = common.settings.currency_code_default%0A        super().__init__(*args, **kwargs)
 %0A%0A%0Ac

clean Money migrations!