from snek.system.form import Form, FormButtonElement, FormInputElement, HTMLElement


class UsernameField(FormInputElement):

    @property
    async def errors(self):
        result = await super().errors
        if self.value and await self.app.services.user.count(username=self.value):
            result.append("Username is not available.")
        return result


class RegisterForm(Form):

    title = HTMLElement(tag="h1", text="Register")

    username = UsernameField(
        name="username",
        required=True,
        min_length=2,
        max_length=20,
        regex=r"^[a-zA-Z0-9_-]+$",
        place_holder="Username",
        type="text",
    )
    email = FormInputElement(
        name="email",
        required=False,
        regex=r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
        place_holder="Email address",
        type="email",
    )
    password = FormInputElement(
        name="password",
        required=True,
        min_length=1,
        type="password",
        place_holder="Password",
    )

    action = FormButtonElement(
        name="action", value="submit", text="Register", type="button"
    )
