# retoor <retoor@molodetz.nl>

from playwright.sync_api import expect

from tests.conftest import BASE_URL


def end_any_active_era():
    from devplacepy.services.game import store

    if store.active_era():
        store.end_era()


def test_admin_game_redirect_unauth(page, app_server):
    page.goto(f"{BASE_URL}/admin/game", wait_until="domcontentloaded")
    assert page.url.startswith(f"{BASE_URL}/auth/login")


def test_admin_game_page_loads_dormant(alice):
    page, _ = alice
    end_any_active_era()
    page.goto(f"{BASE_URL}/admin/game", wait_until="domcontentloaded")
    assert page.is_visible("text=Code Farm - Eras")
    assert page.is_visible("text=No Era is currently running")
    assert page.locator("#era-name").is_visible()


def test_admin_game_start_and_end_era(alice):
    page, _ = alice
    end_any_active_era()
    page.goto(f"{BASE_URL}/admin/game", wait_until="domcontentloaded")
    page.fill("#era-name", "PlaywrightEra")
    page.fill("#era-duration", "14")
    page.click("button:has-text('Start Era')")
    confirm_btn = page.locator(".dialog-confirm")
    confirm_btn.wait_for(state="visible")
    confirm_btn.click()
    page.wait_for_url("**/admin/game", wait_until="domcontentloaded")
    expect(page.locator("text=PlaywrightEra")).to_be_visible()
    assert page.locator("button:has-text('End Era')").is_visible()

    page.click("button:has-text('End Era')")
    confirm_btn = page.locator(".dialog-confirm")
    confirm_btn.wait_for(state="visible")
    confirm_btn.click()
    page.wait_for_url("**/admin/game", wait_until="domcontentloaded")
    assert page.is_visible("text=No Era is currently running")


def test_admin_game_start_form_hidden_while_era_active(alice):
    page, _ = alice
    end_any_active_era()
    page.goto(f"{BASE_URL}/admin/game", wait_until="domcontentloaded")
    page.fill("#era-name", "FirstEra")
    page.click("button:has-text('Start Era')")
    confirm_btn = page.locator(".dialog-confirm")
    confirm_btn.wait_for(state="visible")
    confirm_btn.click()
    page.wait_for_url("**/admin/game", wait_until="domcontentloaded")

    page.goto(f"{BASE_URL}/admin/game", wait_until="domcontentloaded")
    assert page.locator("#era-name").count() == 0
    end_any_active_era()
