from aiohttp import web

from snek.system.markdown import render_markdown


class BaseView(web.View):

    login_required = False

    async def _iter(self):
        if self.login_required and (
            not self.session.get("logged_in") or not self.session.get("uid")
        ):
            return web.HTTPFound("/")
        return await super()._iter()

    @property
    def base_url(self):
        return str(self.request.url.with_path("").with_query(""))

    @property
    def app(self):
        return self.request.app

    @property
    def db(self):
        return self.app.db

    @property
    def services(self):
        return self.app.services

    async def json_response(self, data, **kwargs):
        return web.json_response(data, **kwargs)

    @property
    def session(self):
        return self.request.session

    async def render_template(self, template_name, context=None):
        if template_name.endswith(".md"):
            response = await self.request.app.render_template(
                template_name, self.request, context
            )
            body = await render_markdown(self.app, response.body.decode())
            return web.Response(body=body, content_type="text/html")
        return await self.request.app.render_template(
            template_name, self.request, context
        )


class BaseFormView(BaseView):

    form = None

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

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

    async def post(self):
        form = self.form(app=self.app)
        post = await self.request.json()
        form.set_user_data(post["form"])
        result = await form.to_json()
        if post.get("action") == "validate":
            # Pass
            pass
        if post.get("action") == "submit" and result["is_valid"]:
            result = await self.submit(form)
            return await self.json_response(result)
        return await self.json_response(result)

    async def submit(self, model=None):
        pass
