import pytest

from clarabot_nano.common.spawn.constants import ShortNames
from clarabot_nano_tests.testing.core.instance import CoreTestingNanoInstanceHandler


@pytest.mark.asyncio
async def test_core_request_state_updates(tmpdir, reset_user_app_dirs, dev_nano_root_dir):
    async with CoreTestingNanoInstanceHandler(reset_user_app_dirs, dev_nano_root_dir).run() as (
        pm,
        session,
        children_spawns,
        dbg_config,
    ):
        gateway_pid, gateway_info = next(iter(children_spawns[ShortNames.GATEWAY].items()))

        # test set gateway access
        cv = dbg_config["state"]
        for port, key, ok in [
            (0, b"aaaaaaaa", False),
            (90000, b"aaaaaaaa", False),
            (15000, b"xxxx", False),
            (15000, 849651358, False),
            ("2000", b"xxxxyyyy", False),
            (15000, b"xxxxyyyy", True),
            (15000, b"asdf", False),
            (2000, b"xxxxyyyyzzzz", True),
            (70000, b"xxxxyyyyzzzz", False),
        ]:
            await pm.assert_request_state_update(
                session,
                gateway_info["port"],
                {"_handler_key": "set_gateway_access", "port": port, "key": key},
                ok=ok,
            )
            if ok:
                cv["gateway_port"] = port
                cv["gateway_key"] = key
            dbg_config = pm.get_dbg_config()
            assert dbg_config["state"] == cv
        # extra request with bad message packing
        await pm.assert_request_state_update(session, gateway_info["port"], {}, ok=False, message=b"xxxxxx")
        await pm.wait_children_config(session, children_spawns, fixed_config=dbg_config)
