# Written by retoor@molodetz.nl

# This module defines a web view for user registration. It handles GET requests and form submissions for the registration process.

# The code makes use of 'RegisterForm' from 'snek.form.register' for handling registration forms and 'BaseFormView' from 'snek.system.view' for basic view functionalities.

# MIT License

from aiohttp import web

from snek.form.register import RegisterForm
from snek.system.view import BaseFormView


class RegisterView(BaseFormView):
    form = RegisterForm

    login_required = False

    async def get(self):
        if self.session.get("logged_in"):
            return web.HTTPFound("/web.html")
        if self.request.path.endswith(".json"):
            return await super().get()
        return await self.render_template(
            "register.html", {"form": await self.form(app=self.app).to_json()}
        )

    async def submit(self, form):
        result = await self.app.services.user.register(
            form.email.value, form.username.value, form.password.value
        )
        self.request.session.update(
            {
                "uid": result["uid"],
                "username": result["username"],
                "logged_in": True,
                "color": result["color"],
            }
        )
        return {"redirect_url": "/web.html"}
