from aiohttp import web

from snek.form.settings.profile import SettingsProfileForm
from snek.system.view import BaseFormView


class SettingsProfileView(BaseFormView):
    form = SettingsProfileForm

    login_required = True

    async def get(self):
        form = self.form(app=self.app)

        if self.request.path.endswith(".json"):
            form["nick"] = self.request["user"]["nick"]

            return web.json_response(await form.to_json())

        profile = await self.services.user_property.get(
            self.session.get("uid"), "profile"
        )

        user = await self.services.user.get(uid=self.session.get("uid"))

        return await self.render_template(
            "settings/profile.html",
            {"form": await form.to_json(), "user": user, "profile": profile or ""},
        )

    async def post(self):
        data = await self.request.post()
        user = await self.services.user.get(uid=self.session.get("uid"))

        user["nick"] = data["nick"]
        await self.services.user.save(user)
        await self.services.user_property.set(user["uid"], "profile", data["profile"])
        return web.HTTPFound("/settings/profile.html")
