# retoor <retoor@molodetz.nl>

import json

from tests.conftest import run_async
from devplacepy.services.devii.interaction.broker import InteractionBroker
from devplacepy.services.devii.interaction.controller import InteractionController


def test_ui_prompt_dispatch():
    async def wait_site(interaction_id, frame, timeout):
        return {
            "status": "submitted",
            "interaction_id": interaction_id,
            "values": {"env": "staging"},
        }

    broker = InteractionBroker("main", wait_site=wait_site)
    controller = InteractionController(broker)
    raw = run_async(
        controller.dispatch(
            "ui_prompt",
            {
                "title": "Env?",
                "widgets": [
                    {
                        "type": "choice",
                        "name": "env",
                        "label": "Env",
                        "options": [
                            {"value": "staging", "label": "Staging"},
                            {"value": "prod", "label": "Prod"},
                        ],
                    }
                ],
            },
        )
    )
    data = json.loads(raw)
    assert data["status"] == "submitted"
    assert data["values"]["env"] == "staging"


def test_ui_notify_on_site():
    events = []

    async def emit(payload):
        events.append(payload)

    broker = InteractionBroker("main", emit=emit)
    controller = InteractionController(broker)
    raw = run_async(controller.dispatch("ui_notify", {"text": "Working..."}))
    data = json.loads(raw)
    assert data["status"] == "ok"
    assert events and events[0]["type"] == "status"
