# Written by retoor@molodetz.nl

# This source code defines a LoginView class that inherits from BaseFormView and handles user authentication. It checks if a user is logged in, provides a JSON response or renders a login HTML template as needed, and processes form submissions to authenticate users.

# The code imports the LoginForm from snek.form.login and BaseFormView from snek.system.view, both of which are likely custom modules in the system, as well as web from aiohttp for handling HTTP responses.

# MIT License

from aiohttp import web

from snek.form.login import LoginForm
from snek.system.view import BaseFormView


class LoginView(BaseFormView):
    form = LoginForm

    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(
            "login.html", {"form": await self.form(app=self.app).to_json()}
        )

    async def submit(self, form):
        if await form.is_valid:
            user = await self.services.user.get(
                username=form["username"], deleted_at=None
            )
            await self.services.user.save(user)
            self.session.update(
                {
                    "logged_in": True,
                    "username": user["username"],
                    "uid": user["uid"],
                    "color": user["color"],
                }
            )
            return {"redirect_url": "/web.html"}
        return {"is_valid": False}
