import pytest

from clarabot_nano.utility import parse_environment_flag
from clarabot_nano_tests.testing.control import run_nano_control_tester
from clarabot_nano_tests.testing.server.manager import DevServerManager


async def _run_control_window_tests(
    tmpdir,
    reset_user_app_dirs,
    dev_nano_root_dir,
    testing_server_manager: DevServerManager,
    testing_server_user0,
    expected_update_state,
):
    """
    Test:
        - update state handling
    """
    test_log = await run_nano_control_tester(
        tmpdir,
        testing_server_manager,
        reset_user_app_dirs,
        dev_nano_root_dir,
        "clarabot_nano_tests.control.cases._update_state:_UpdateStateControlApplicationTester",
        {
            "email": testing_server_user0["email"],
            "password": testing_server_user0["password"],
            "expected_update_state": expected_update_state,
        },
        timeout=20.0,
    )
    target_log = [
        "Starting _UpdateStateControlApplicationTester",
        "Systray available: True",
        "Phase 0 passed.",
        "Phase 1 passed.",
        "Phase 2 passed.",
        "Phase 3 passed.",
        "Test phases passed.",
        "Exiting",
        "",
    ]
    assert test_log == target_log, test_log


@pytest.mark.skipif(parse_environment_flag("CBNANO_TEST_WITHOUT_SERVER"), reason="server-dependant tests disabled")
@pytest.mark.parametrize("expected_update_state", [-1, 0, 1, 2, 3, 4, 999])
@pytest.mark.asyncio
async def test_control_window_update_states(
    tmpdir,
    reset_user_app_dirs,
    dev_nano_root_dir,
    testing_server_manager: DevServerManager,
    testing_server_user0,
    expected_update_state,
):
    await testing_server_manager.call_nano_update_state_override(expected_update_state)
    try:
        await _run_control_window_tests(
            tmpdir,
            reset_user_app_dirs,
            dev_nano_root_dir,
            testing_server_manager,
            testing_server_user0,
            expected_update_state,
        )
    finally:
        await testing_server_manager.call_nano_update_state_override(None)
