import pathlib

from aiohttp import web
from app.app import Application as BaseApplication

from snek.system.markdown import MarkdownExtension


class Application(BaseApplication):

    def __init__(self, path=None, *args, **kwargs):
        self.path = pathlib.Path(path)
        template_path = self.path

        super().__init__(template_path=template_path, *args, **kwargs)
        self.jinja2_env.add_extension(MarkdownExtension)

        self.router.add_get("/{tail:.*}", self.handle_document)

    async def handle_document(self, request):
        relative_path = request.match_info["tail"].strip("/")
        if relative_path == "":
            relative_path = "index.html"
        document_path = self.path.joinpath(relative_path)
        if not document_path.exists():
            return web.Response(
                status=404,
                body=b"Resource is not found on this server.",
                content_type="text/plain",
            )
        if document_path.is_dir():
            document_path = document_path.joinpath("index.html")
        if not document_path.exists():
            return web.Response(
                status=404,
                body=b"Resource is not found on this server.",
                content_type="text/plain",
            )

        response = await self.render_template(
            str(document_path.relative_to(self.path)), request
        )
        return response
