"""Configuration du systeme dans Chrome : sections, navigation, enregistrement."""
import importlib.util
import re
from unittest import skipUnless

from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse

from facturation import tests_quick_billing_browser as quick_browser
from facturation.models import Configuration


@skipUnless(importlib.util.find_spec("playwright"), "Installer requirements-dev.txt pour les tests Chrome.")
class ConfigurationSettingsBrowserTests(StaticLiveServerTestCase):
    browser = quick_browser.QuickBillingBrowserTests.browser

    def setUp(self):
        quick_browser.QuickBillingBrowserTests.setUp(self)
        configuration = Configuration.objects.get()
        self.initial_rate = configuration.taux_change
        self.initial_vat = configuration.tva_percent

    def open_settings(self, page):
        page.goto(self.live_server_url + reverse("facturation:configuration"), wait_until="load")

    def test_sections_navigation_unsaved_changes_errors_and_save(self):
        from playwright.sync_api import expect

        with self.browser(viewport={"width": 1366, "height": 768}) as page:
            self.open_settings(page)
            links = page.locator(".fc-settings-nav-link")
            expect(links).to_have_count(5)
            expect(page.locator(".fc-settings-card")).to_have_count(5)
            expect(links.first).to_have_class(re.compile(r"\bis-active\b"))
            expect(links.first).to_have_text("Informations entreprise")
            expect(page.locator(".fc-settings-nav-group").last).to_have_text("Factures")
            expect(links.last).to_have_text("Format d'impression")
            expect(page.locator("#cfg-impression-title")).to_have_text("Format d'impression")
            page.screenshot(path=str(self.qa_dir / "settings-fr-desktop.png"))

            emcf_link = page.locator('.fc-settings-nav-link[href="#cfg-emcf"]')
            emcf_link.click()
            expect(emcf_link).to_have_class(re.compile(r"\bis-active\b"))
            expect(page.locator("#cfg-emcf")).to_be_in_viewport()

            status = page.locator("[data-settings-status]")
            expect(status).to_have_text("Aucune modification en attente.")
            expect(page.locator("#id_taux_change")).to_have_count(0)
            expect(page.locator("#id_tva_percent")).to_have_count(0)
            page.locator("#id_nom_entreprise").fill("FacControl test")
            expect(status).to_have_text("Modifications non enregistrées.")
            expect(page.locator(".fc-settings-savebar")).to_have_class(re.compile(r"\bis-dirty\b"))

            token = page.locator("#id_edef_api_token")
            expect(token).to_have_attribute("type", "password")
            page.locator("[data-settings-reveal]").click()
            expect(token).to_have_attribute("type", "text")

            # Token obligatoire absent : la section e-MCF est signalee.
            page.locator(".fc-settings-savebar button[type=submit]").click()
            expect(page.locator(".fc-settings-notice.is-error")).to_be_visible()
            expect(emcf_link.locator(".fc-settings-nav-dot")).to_have_count(1)
            expect(page.locator("#cfg-emcf .fc-settings-error")).to_be_visible()
            page.screenshot(path=str(self.qa_dir / "settings-fr-error.png"))

            page.locator("#id_edef_api_token").fill("token-test")
            page.locator(".fc-settings-savebar button[type=submit]").click()
            page.wait_for_url(lambda url: "/configuration/" not in url)
        # Hors de la session Playwright : l'ORM synchrone y est interdit.
        configuration = Configuration.objects.get()
        self.assertEqual(configuration.taux_change, self.initial_rate)
        self.assertEqual(configuration.tva_percent, self.initial_vat)
        self.assertEqual(configuration.nom_entreprise, "FacControl test")

    def test_mobile_english_dark_layout_stays_within_the_screen(self):
        from playwright.sync_api import expect

        dark = "try { localStorage.setItem('faccontrol-theme', 'dark'); } catch (error) {}"
        with self.browser(language="en", viewport={"width": 390, "height": 844}, init_script=dark) as page:
            self.open_settings(page)
            # Pas de titre en double au-dessus de la navigation de sections.
            expect(page.locator(".pagetitle")).to_have_count(0)
            expect(page).to_have_title(re.compile("System configuration"))
            expect(page.locator(".fc-settings-nav-link").first).to_have_text("Company information")
            expect(page.locator("#cfg-emcf-title")).to_have_text("e-MCF/MCF connection")
            expect(page.locator("#cfg-impression-title")).to_have_text("Print format")
            expect(page.locator("#cfg-impression")).to_contain_text("A4 (standard sheet)")
            self.assertTrue(page.evaluate("document.documentElement.scrollWidth <= window.innerWidth"))
            page.screenshot(path=str(self.qa_dir / "settings-en-mobile-dark.png"), full_page=True)
