from django.test import tag
from playwright.sync_api import expect
from django.conf import settings as s
from .frontend_base import EnviPyStaticLiveServerTestCase


class TestLoginPage(EnviPyStaticLiveServerTestCase):
    @tag("frontend")
    def test_register(self):
        page = self.page
        page.goto(self.live_server_url + "/login")
        page.get_by_text("Register", exact=True).click()
        page.get_by_role("textbox", name="Username").click()
        page.get_by_role("textbox", name="Username").fill("newuser")
        page.get_by_role("textbox", name="Email").click()
        page.get_by_role("textbox", name="Email").fill("newuser@new.com")
        page.get_by_role("textbox", name="Password", exact=True).click()
        page.get_by_role("textbox", name="Password", exact=True).fill("NewUser_1")
        page.get_by_role("textbox", name="Repeat Password").click()
        page.get_by_role("textbox", name="Repeat Password").fill("NewUser_1")
        page.get_by_role("button", name="Sign Up").click()

        if s.ADMIN_APPROVAL_REQUIRED:
            expected_text = "Your account has been created! An admin will activate it soon!"
        else:
            expected_text = (
                "Account has been created! You'll receive a mail to activate your account shortly."
            )
        # Check for success text after Sign Up is clicked
        expect(page.get_by_text(expected_text)).to_be_visible(timeout=10000)

        if s.ADMIN_APPROVAL_REQUIRED:
            from django.contrib.auth import get_user_model

            u = get_user_model().objects.get(username="newuser")
            u.is_active = True
            u.save()

        page.get_by_role("textbox", name="Account").click()
        page.get_by_role("textbox", name="Account").fill("newuser")
        page.get_by_role("textbox", name="Password").click()
        page.get_by_role("textbox", name="Password").fill("NewUser_1")
        page.get_by_role("button", name="Sign In").click()
        # Check that the logged in button is visible indicating the user is logged in
        expect(page.locator("#loggedInButton")).to_be_visible(timeout=100000000)

    @tag("frontend")
    def test_login(self):
        page = self.login()
        # Check that the logged in button is visible indicating the user is logged in
        expect(page.locator("#loggedInButton")).to_be_visible()
