# -*- coding: utf-8 -*-
"""
UI元素类 - 无障碍元素操作
"""

from typing import Optional, Dict, Any, TYPE_CHECKING

if TYPE_CHECKING:
    from .device import Device


class Element:
    """
    UI元素类
    
    代表屏幕上的一个可交互元素（按钮、文本框等）
    
    Example:
        >>> element = device.find_element(text="登录")
        >>> element.click()
        >>> print(element.text)
    """
    
    def __init__(self, device: "Device", info: dict):
        """
        初始化元素
        
        Args:
            device: 所属设备
            info: 元素信息
        """
        self._device = device
        self._info = info
    
    @property
    def text(self) -> str:
        """元素文字"""
        return self._info.get("text", "")
    
    @property
    def resource_id(self) -> str:
        """元素ID"""
        return self._info.get("resource_id", "")
    
    @property
    def class_name(self) -> str:
        """元素类名"""
        return self._info.get("class_name", "")
    
    @property
    def content_desc(self) -> str:
        """内容描述"""
        return self._info.get("content_desc", "")
    
    @property
    def bounds(self) -> Dict[str, int]:
        """
        元素边界坐标
        
        Returns:
            {"left": x1, "top": y1, "right": x2, "bottom": y2}
        """
        return self._info.get("bounds", {})
    
    @property
    def center(self) -> tuple:
        """
        元素中心坐标
        
        Returns:
            (x, y)
        """
        bounds = self.bounds
        if bounds:
            x = (bounds.get("left", 0) + bounds.get("right", 0)) // 2
            y = (bounds.get("top", 0) + bounds.get("bottom", 0)) // 2
            return (x, y)
        return (0, 0)
    
    @property
    def clickable(self) -> bool:
        """是否可点击"""
        return self._info.get("clickable", False)
    
    @property
    def enabled(self) -> bool:
        """是否启用"""
        return self._info.get("enabled", True)
    
    @property
    def focused(self) -> bool:
        """是否获得焦点"""
        return self._info.get("focused", False)
    
    @property
    def selected(self) -> bool:
        """是否选中"""
        return self._info.get("selected", False)
    
    @property
    def checked(self) -> bool:
        """是否勾选"""
        return self._info.get("checked", False)
    
    @property
    def scrollable(self) -> bool:
        """是否可滚动"""
        return self._info.get("scrollable", False)
    
    def click(self) -> bool:
        """
        点击元素
        
        Returns:
            是否成功
        """
        x, y = self.center
        if x and y:
            return self._device.click(x, y)
        
        # 使用无障碍直接点击
        result = self._device._send_command({
            "action": "click_element",
            "element_id": self._info.get("id")
        })
        return result.get("success", False)
    
    def long_click(self, duration: int = 1000) -> bool:
        """
        长按元素
        
        Args:
            duration: 按压时长(毫秒)
        """
        x, y = self.center
        if x and y:
            return self._device.long_press(x, y, duration)
        return False
    
    def input_text(self, text: str) -> bool:
        """
        向元素输入文字
        
        Args:
            text: 要输入的文字
        """
        # 先点击获取焦点
        self.click()
        # 然后输入
        return self._device.input_text(text)
    
    def clear_text(self) -> bool:
        """清空文字"""
        self.click()
        return self._device.clear_text()
    
    def set_text(self, text: str) -> bool:
        """
        设置文字（清空后输入）
        
        Args:
            text: 要设置的文字
        """
        result = self._device._send_command({
            "action": "set_element_text",
            "element_id": self._info.get("id"),
            "text": text
        })
        return result.get("success", False)
    
    def scroll_forward(self) -> bool:
        """向前滚动（向下/向右）"""
        if self.scrollable:
            result = self._device._send_command({
                "action": "scroll_element",
                "element_id": self._info.get("id"),
                "direction": "forward"
            })
            return result.get("success", False)
        return False
    
    def scroll_backward(self) -> bool:
        """向后滚动（向上/向左）"""
        if self.scrollable:
            result = self._device._send_command({
                "action": "scroll_element",
                "element_id": self._info.get("id"),
                "direction": "backward"
            })
            return result.get("success", False)
        return False
    
    def exists(self) -> bool:
        """
        判断元素是否仍然存在
        
        Returns:
            是否存在
        """
        element = self._device.find_element(
            text=self.text if self.text else None,
            resource_id=self.resource_id if self.resource_id else None
        )
        return element is not None
    
    def wait_gone(self, timeout: float = 10) -> bool:
        """
        等待元素消失
        
        Args:
            timeout: 超时时间(秒)
        
        Returns:
            是否消失
        """
        import time
        start_time = time.time()
        
        while (time.time() - start_time) < timeout:
            if not self.exists():
                return True
            time.sleep(0.5)
        
        return False
    
    def get_parent(self) -> Optional["Element"]:
        """获取父元素"""
        result = self._device._send_command({
            "action": "get_element_parent",
            "element_id": self._info.get("id")
        })
        
        if result.get("found"):
            return Element(self._device, result.get("element", {}))
        return None
    
    def get_children(self) -> list:
        """获取子元素列表"""
        result = self._device._send_command({
            "action": "get_element_children",
            "element_id": self._info.get("id")
        })
        
        children = []
        for elem_info in result.get("elements", []):
            children.append(Element(self._device, elem_info))
        return children
    
    def find_child(
        self,
        text: str = None,
        resource_id: str = None,
        class_name: str = None
    ) -> Optional["Element"]:
        """在子元素中查找"""
        result = self._device._send_command({
            "action": "find_child_element",
            "parent_id": self._info.get("id"),
            "text": text,
            "resource_id": resource_id,
            "class_name": class_name
        })
        
        if result.get("found"):
            return Element(self._device, result.get("element", {}))
        return None
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "text": self.text,
            "resource_id": self.resource_id,
            "class_name": self.class_name,
            "content_desc": self.content_desc,
            "bounds": self.bounds,
            "center": self.center,
            "clickable": self.clickable,
            "enabled": self.enabled,
            "focused": self.focused,
            "selected": self.selected,
            "checked": self.checked,
            "scrollable": self.scrollable
        }
    
    def __repr__(self):
        text_preview = self.text[:20] + "..." if len(self.text) > 20 else self.text
        return f"<Element text='{text_preview}' id='{self.resource_id}'>"
    
    def __bool__(self):
        """支持 if element: 语法"""
        return True
