import os

from django.conf import settings as s
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core.management import call_command
from django.test import override_settings
from playwright.sync_api import sync_playwright


@override_settings(MODEL_DIR=s.FIXTURE_DIRS[0] / "models", CELERY_TASK_ALWAYS_EAGER=True)
class EnviPyStaticLiveServerTestCase(StaticLiveServerTestCase):
    fixtures = ["test_fixtures_incl_model.jsonl.gz"]

    @staticmethod
    def repair_polymorphic_ctypes():
        from django.contrib.contenttypes.models import ContentType

        from epdb.models import EPModel

        for obj in EPModel.objects.filter(polymorphic_ctype__isnull=True):
            obj.polymorphic_ctype = ContentType.objects.get_for_model(obj.__class__)
            obj.save(update_fields=["polymorphic_ctype"])

    @classmethod
    def setUpClass(cls):
        os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
        super().setUpClass()

        cls.playwright = sync_playwright().start()
        cls.browser = cls.playwright.chromium.launch()
        cls.username = "user0"
        cls.password = "SuperSafe"

    def setUp(self):
        # DB gets flushed after each test and rolled back to initial fixture state.
        # Hence, we have to localize the urls per test.
        # The fixtures have "http://localhost:8000/" in all of the URLs
        # Use the custom mgmt command to adjust it to the current live_server_url
        call_command("localize_urls", old="http://localhost:8000/", new=f"{self.live_server_url}/")

        # Fix broken polymorphic ctypes
        EnviPyStaticLiveServerTestCase.repair_polymorphic_ctypes()

        s.SERVER_URL = self.live_server_url
        self.context = self.browser.new_context()
        self.page = self.context.new_page()

    def tearDown(self):
        self.page.wait_for_load_state("networkidle")
        self.page.close()

    @classmethod
    def tearDownClass(cls):
        cls.browser.close()
        cls.playwright.stop()
        super().tearDownClass()

    def login(self):
        """Sign in with the test user, 'user0'"""
        self.page.goto(self.live_server_url + "/login")
        self.page.get_by_role("textbox", name="Account").click()
        self.page.get_by_role("textbox", name="Account").fill(self.username)
        self.page.get_by_role("textbox", name="Password").click()
        self.page.get_by_role("textbox", name="Password").fill(self.password)

        with self.page.expect_navigation():
            self.page.get_by_role("button", name="Sign In").click()

        return self.page
