
import re

from django.forms import ValidationError

from dext.forms import forms, fields

from utg import relations as utg_relations

from the_tale.linguistics import forms as word_forms

from the_tale.game.relations import GENDER, RACE

from the_tale.game.heroes import models
from the_tale.game.heroes import conf


NAME_REGEX = re.compile(conf.heroes_settings.NAME_REGEX)


class EditNameForm(forms.Form):

    race = fields.TypedChoiceField(label='раса', choices=RACE.choices(), coerce=RACE.get_from_name)
    gender = fields.TypedChoiceField(label='пол', choices=GENDER.choices(), coerce=GENDER.get_from_name)
    name = word_forms.WordField(word_type=utg_relations.WORD_TYPE.NOUN,
                                widget_class=word_forms.SimpleNounWidget,
                                label='имя',
                                skip_markers=(utg_relations.NOUN_FORM.COUNTABLE, utg_relations.NUMBER.PLURAL),
                                show_properties=False)

    def clean(self):
        cleaned_data = super(EditNameForm, self).clean()

        name = cleaned_data.get('name')

        if name is not None:
            for name_form in cleaned_data['name'].forms:
                if len(name_form) > models.Hero.MAX_NAME_LENGTH:
                    raise ValidationError('Слишком длинное имя, максимальное число символов: %d' % models.Hero.MAX_NAME_LENGTH)

                if len(name_form) < conf.heroes_settings.NAME_MIN_LENGHT:
                    raise ValidationError('Слишком короткое имя, минимальное число символов: %d' % conf.heroes_settings.NAME_MIN_LENGHT)

                if NAME_REGEX.match(name_form) is None:
                    raise ValidationError('Имя героя может содержать только следующие символы: %s' % conf.heroes_settings.NAME_SYMBOLS_DESCRITION)

            name.properties = name.properties.clone(cleaned_data['gender'].utg_id,
                                                    utg_relations.NUMBER.SINGULAR)

        return cleaned_data

    @classmethod
    def get_initials(cls, hero):
        return {'gender': hero.gender,
                'race': hero.race,
                'name':  hero.utg_name }
