from wtforms.fields.simple import StringField
from wtforms.validators import ValidationError
from app.models.tag import TagInformation

def tag_validator(form, field):
    all_tags = TagInformation.all_tags()
    for name in field.selected_tags():
        if all(ti.id != name for ctgy in all_tags for ti in all_tags[ctgy]):
            raise ValidationError(f"Tag inconnu: {name}")
    return True

class TagListField(StringField):

    def __init__(self, title, *args, **kwargs):
        validators = kwargs.get("validators", []) + [tag_validator]
        super().__init__(
            title,
            *args,
            **kwargs,
            validators=[tag_validator])

    def selected_tags(self):
        raw = map(lambda x: x.strip(), self.data.split(","))
        return [name for name in raw if name != ""]
