"""
macOS平台拖拽检测器

使用macOS Cocoa API实现系统级拖拽检测。
"""

import os
import sys
import time
import threading
from typing import List, Optional
from .base_detector import BaseDragDetector


class MacOSDragDetector(BaseDragDetector):
    """macOS平台拖拽检测器"""
    
    def __init__(self, supported_formats: List[str] = None):
        """
        初始化macOS拖拽检测器
        
        Args:
            supported_formats: 支持的文件格式列表
        """
        super().__init__(supported_formats)
        self._app_kit_available = self._check_app_kit()
        self._cocoa_available = self._check_cocoa()
        
    def _check_app_kit(self) -> bool:
        """检查AppKit是否可用"""
        try:
            import AppKit
            return True
        except ImportError:
            return False
            
    def _check_cocoa(self) -> bool:
        """检查Cocoa是否可用"""
        try:
            import Cocoa
            return True
        except ImportError:
            return False
            
    def _setup_cocoa_drag_drop(self) -> bool:
        """设置Cocoa拖拽接收"""
        try:
            if not self._app_kit_available:
                return False
                
            import AppKit
            
            # 创建拖拽接收器
            # 这里需要实现macOS的拖拽API调用
            # 暂时返回False，需要进一步实现
            return False
        except Exception as e:
            print(f"设置Cocoa拖拽失败: {e}")
            return False
            
    def _monitor_file_drag(self):
        """通过文件系统变化监控拖拽"""
        # 监控用户桌面和下载目录
        desktop_path = os.path.expanduser("~/Desktop")
        downloads_path = os.path.expanduser("~/Downloads")
        
        watch_dirs = [desktop_path, downloads_path]
        
        while self.is_running:
            try:
                current_time = time.time()
                for watch_dir in watch_dirs:
                    if not os.path.exists(watch_dir):
                        continue
                        
                    for filename in os.listdir(watch_dir):
                        filepath = os.path.join(watch_dir, filename)
                        try:
                            file_time = os.path.getmtime(filepath)
                            # 如果文件是最近1秒内创建的
                            if current_time - file_time < 1.0:
                                if self._is_supported_format(filepath):
                                    self.add_dropped_file(filepath)
                        except OSError:
                            continue
                            
            except Exception as e:
                print(f"文件拖拽监控错误: {e}")
                
            time.sleep(0.5)
            
    def _monitor_loop(self):
        """主监控循环"""
        if self._app_kit_available and self._cocoa_available:
            # 尝试设置真正的拖拽接收
            if not self._setup_cocoa_drag_drop():
                # 降级到文件系统监控
                self._monitor_file_drag()
        else:
            # 降级到文件系统监控
            self._monitor_file_drag()
            
    def is_supported(self) -> bool:
        """检查macOS平台是否支持"""
        return sys.platform.startswith('darwin')