from aiohttp import web

from snek.system.view import BaseFormView


class RepositoriesIndexView(BaseFormView):

    login_required = True

    async def get(self):

        user_uid = self.session.get("uid")

        repositories = []
        async for repository in self.services.repository.find(user_uid=user_uid):
            repositories.append(repository.record)

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

        return await self.render_template(
            "settings/repositories/index.html",
            {"repositories": repositories, "user": user},
        )


class RepositoriesCreateView(BaseFormView):

    login_required = True

    async def get(self):

        return await self.render_template("settings/repositories/create.html")

    async def post(self):
        data = await self.request.post()
        await self.services.repository.create(
            user_uid=self.session.get("uid"),
            name=data["name"],
            is_private=int(data.get("is_private", 0)),
        )
        return web.HTTPFound("/settings/repositories/index.html")


class RepositoriesUpdateView(BaseFormView):

    login_required = True

    async def get(self):

        repository = await self.services.repository.get(
            user_uid=self.session.get("uid"), name=self.request.match_info["name"]
        )
        if not repository:
            return web.HTTPNotFound()
        return await self.render_template(
            "settings/repositories/update.html", {"repository": repository.record}
        )

    async def post(self):
        data = await self.request.post()
        repository = await self.services.repository.get(
            user_uid=self.session.get("uid"), name=self.request.match_info["name"]
        )
        repository["is_private"] = int(data.get("is_private", 0))
        await self.services.repository.save(repository)
        return web.HTTPFound("/settings/repositories/index.html")


class RepositoriesDeleteView(BaseFormView):

    login_required = True

    async def get(self):

        repository = await self.services.repository.get(
            user_uid=self.session.get("uid"), name=self.request.match_info["name"]
        )
        if not repository:
            return web.HTTPNotFound()

        return await self.render_template(
            "settings/repositories/delete.html", {"repository": repository.record}
        )

    async def post(self):
        user_uid = self.session.get("uid")
        name = self.request.match_info["name"]
        repository = await self.services.repository.get(user_uid=user_uid, name=name)
        if not repository:
            return web.HTTPNotFound()
        await self.services.repository.delete(user_uid=user_uid, name=name)
        return web.HTTPFound("/settings/repositories/index.html")
