import sys

from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import (
    QApplication,
    QPushButton,
    QStackedWidget,
    QWidget,
)

from modules.agent_workspace import (
    EmbeddedAgentWorkspace,
)


app = QApplication.instance() or QApplication(
    sys.argv
)

stack = QStackedWidget()

home = QWidget()
agents = QWidget()

stack.addWidget(home)
stack.addWidget(agents)

workspace = EmbeddedAgentWorkspace(
    stack,
    agents,
    {
        "id": "scanforge",
        "name": "ScanForge Scanner Agent",
        "workspaceUrl": (
            "http://127.0.0.1:8785/"
            "agents/scanforge/"
        ),
    },
)

stack.addWidget(workspace)
stack.setCurrentWidget(workspace)

result = {
    "finished": False,
    "successful": False,
}


def finished(successful):
    result["finished"] = True
    result["successful"] = bool(successful)

    for object_name in (
        "agentWorkspaceHome",
        "agentWorkspaceBack",
        "agentWorkspaceReload",
    ):
        button = workspace.findChild(
            QPushButton,
            object_name,
        )

        if button is None:
            raise RuntimeError(
                f"Missing control: {object_name}"
            )

    token_length = len(
        workspace._workspace_token()
    )

    if token_length < 20:
        raise RuntimeError(
            "Workspace token was not loaded."
        )

    print("loadFinished:", bool(successful))
    print(
        "url:",
        workspace.view.url().toString(),
    )
    print("HOME control: PASS")
    print("BACK TO AGENTS control: PASS")
    print("RELOAD control: PASS")
    print(
        "Private token loaded: PASS "
        f"(length {token_length})"
    )

    QTimer.singleShot(
        300,
        app.quit,
    )


workspace.view.loadFinished.connect(
    finished
)

workspace.reload_workspace()

QTimer.singleShot(
    15000,
    app.quit,
)

app.exec_()

if not result["finished"]:
    raise SystemExit(
        "Embedded workspace never finished loading."
    )

if not result["successful"]:
    raise SystemExit(
        "Embedded workspace load failed."
    )

print("QT EMBEDDED SCANFORGE WORKSPACE: PASS")
