"""UI 控件操作 Mixin — ui_match, ui_exist"""

from __future__ import annotations

from typing import TYPE_CHECKING, List, Optional

if TYPE_CHECKING:
    from ..device import Device
    from ..selector import UiObject


class UiMixin:
    """UI 控件操作"""

    _client: ...

    def ui_match(self, all_window: bool = False, match_from_cache: bool = False, 
                 limit: int = 9999, **match_params) -> List["UiObject"]:
        """扫描屏幕 UI 控件并匹配
        
        Args:
            all_window: 是否查找所有窗口 (含悬浮窗)
            match_from_cache: 是否从缓存匹配
            limit: 最大返回数量
            **match_params: 匹配参数 (text, res, desc, cls, pkg...)
        """
        from ..selector import Selector, UiObject
        params = dict(Selector(**match_params))
        params["all_window"] = str(all_window).lower()
        params["match_from_cache"] = str(match_from_cache).lower()
        params["limit"] = str(limit)

        result = self._client.auto_api("/uia_match", params)
        nodes = []
        if isinstance(result, list):
            for item in result:
                if isinstance(item, dict):
                    sel = Selector(**match_params)
                    # 可以在这里根据 item 构造更精确的 selector，或者直接构造 UiObject
                    obj = UiObject(self, sel)  # type: ignore
                    nodes.append(obj)
        return nodes

    def ui_exist(self, **match_params) -> bool:
        """检查符合条件的控件是否存在"""
        return len(self.ui_match(limit=1, **match_params)) > 0

    def wait_for_ui(self, timeout: float = 10, interval: float = 0.5, **match_params) -> Optional["UiObject"]:
        """等待屏幕出现符合条件的 UI 控件"""
        import time
        deadline = time.time() + timeout
        while time.time() < deadline:
            res = self.ui_match(limit=1, **match_params)
            if res:
                return res[0]
            time.sleep(interval)
        return None
