# -*- coding: utf-8 -*-
from importlib import import_module
from pathlib import Path

from django.template.loader import get_template
from django.test import TestCase
from wagtail.models import Page

from ocyan.plugin.roadrunner_bs5.models import RoadrunnerPage
from rr.fields import RoadRunnerField


class RoadrunnerBs5SmokeTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.root = Page.objects.get(id=1)
        cls.page = RoadrunnerPage(
            title="Roadrunner smoke page", slug="roadrunner-smoke"
        )
        cls.root.add_child(instance=cls.page)
        cls.page.save_revision().publish()

    def test_app_import(self):
        module = import_module("ocyan.plugin.roadrunner_bs5")
        self.assertTrue(hasattr(module, "RoadrunnerBootstrap5Config"))

    def test_page_model_import(self):
        self.assertEqual(RoadrunnerPage.__name__, "RoadrunnerPage")
        self.assertEqual(RoadrunnerPage._meta.verbose_name, "Roadrunner layout page")

    def test_roadrunner_page_template_loads(self):
        template = get_template("roadrunner/roadrunner_page.html")
        self.assertIsNotNone(template)

    def test_packaged_roadrunner_page_template_uses_compiled_css(self):
        packaged_template = (
            Path(__file__).resolve().parent
            / "templates"
            / "roadrunner"
            / "roadrunner_page.html"
        )
        template_source = packaged_template.read_text(encoding="utf-8")
        self.assertIn("roadrunner_bs5/css/style.css", template_source)
        self.assertNotIn('type="text/x-scss"', template_source)

    def test_resolved_roadrunner_page_template_avoids_runtime_scss(self):
        template = get_template("roadrunner/roadrunner_page.html")
        template_source = Path(template.origin.name).read_text(encoding="utf-8")
        self.assertNotIn('type="text/x-scss"', template_source)

    def test_roadrunner_page_field_type(self):
        self.assertIsInstance(
            RoadrunnerPage._meta.get_field("content"), RoadRunnerField
        )

    def test_wagtail_hooks_imports(self):
        module = import_module("ocyan.plugin.roadrunner_bs5.wagtail_hooks")
        self.assertIsNotNone(module)

    def test_roadrunner_page_is_creatable_under_root(self):
        root = Page.objects.get(id=1)
        creatable = root.specific_class.creatable_subpage_models()
        self.assertIn(RoadrunnerPage, creatable)
