"""
Formulaire configuration des codes Apo et EDT des modimps d'un formsemestre
"""

from flask_wtf import FlaskForm
from wtforms import validators
from wtforms.fields.simple import StringField, SubmitField

from app.models import FormSemestre, ModuleImpl


class _EditModimplsCodesForm(FlaskForm):
    "form. définition des liens personnalisés"
    # construit dynamiquement ci-dessous


def EditModimplsCodesForm(formsemestre: FormSemestre) -> _EditModimplsCodesForm:
    "Création d'un formulaire pour éditer les codes"

    # Formulaire dynamique, on créé une classe ad-hoc
    class F(_EditModimplsCodesForm):
        pass

    def _gen_mod_form(modimpl: ModuleImpl):
        field = StringField(
            modimpl.module.code,
            validators=[
                validators.Optional(),
                validators.Length(min=1, max=80),
            ],
            default="",
            render_kw={"size": 32},
        )
        setattr(F, f"modimpl_apo_{modimpl.id}", field)
        field = StringField(
            "",
            validators=[
                validators.Optional(),
                validators.Length(min=1, max=80),
            ],
            default="",
            render_kw={"size": 12},
        )
        setattr(F, f"modimpl_edt_{modimpl.id}", field)

    for modimpl in formsemestre.modimpls_sorted:
        _gen_mod_form(modimpl)

    F.submit = SubmitField("Valider")
    F.cancel = SubmitField("Annuler", render_kw={"formnovalidate": True})

    return F()
