""" This module holds the forms of the ``translation`` app. """

from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError

from .models import TranslatableLanguage
from .utils import get_available_languages_code


class LanguageForm(forms.ModelForm):
    """ Language form which limited language choices to languages available.
    We use settings.LANGUAGES to populate language choices removing languages already translated.
    """

    class Meta:
        model = TranslatableLanguage
        fields = ('language',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['language'].choices = self.get_remaining_languages()

    def get_remaining_languages(self):
        """ Return remaining languages which not yet used. """
        return [(code, name) for code, name in settings.LANGUAGES
                if code not in get_available_languages_code()]

    def validate_unique(self):
        """ If instance is not valid, this means that there is another
        instance of this language. So we enable this other instance. """
        try:
            self.instance.validate_unique()
        except ValidationError:
            self.instance = TranslatableLanguage.objects.get(language=self.instance.language)
            self.instance.enabled = True
