from __future__ import annotations

import importlib.util
import tempfile
import unittest
from pathlib import Path

from exile import AsyncTestClient, Exile, render_template, render_template_async

HAS_JINJA2 = importlib.util.find_spec("jinja2") is not None


@unittest.skipUnless(HAS_JINJA2, "jinja2 is not installed")
class TemplatingTests(unittest.IsolatedAsyncioTestCase):
    async def test_render_template_in_request_context(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            (root / "hello.html").write_text("<h1>{{ title }}</h1>", encoding="utf-8")

            app = Exile(__name__, static_folder=None, template_folder=tmpdir)

            @app.get("/hello")
            def hello():
                return render_template("hello.html", title="Exile")

            client = AsyncTestClient(app)
            response = await client.get("/hello")

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.text, "<h1>Exile</h1>")

    async def test_template_can_use_url_for(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            (root / "link.html").write_text("{{ url_for('user_detail', user_id=9) }}", encoding="utf-8")

            app = Exile(__name__, static_folder=None, template_folder=tmpdir)

            @app.get("/users/<int:user_id>")
            def user_detail(user_id: int):
                return {"user_id": user_id}

            @app.get("/link")
            def link():
                return render_template("link.html")

            client = AsyncTestClient(app)
            response = await client.get("/link")

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.text, "/users/9")

    async def test_render_template_async_helper(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            (root / "hello_async.html").write_text("<p>{{ title }}</p>", encoding="utf-8")

            app = Exile(__name__, static_folder=None, template_folder=tmpdir)

            @app.get("/hello-async")
            async def hello_async():
                return await render_template_async("hello_async.html", title="Async")

            client = AsyncTestClient(app)
            response = await client.get("/hello-async")

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.text, "<p>Async</p>")


if __name__ == "__main__":
    unittest.main()
