# -*- coding: utf-8 -*-
"""Dialog views for destructive actions, selection, remote connect, and KV editing."""

from util.runtime import *
from util.utils import node_host_only, _server_id_sort_key
from models.config import Config
from controllers.workers import ClearDatabaseThread, NodeStatusCheckWorker
from views.common import (
    ServerIdTableItem,
    NoWheelComboBox,
    apply_button_style,
    set_button_icon,
)

class ServerSelectDialog(QDialog):
    """服务器选择对话框"""
    
    def __init__(self, config: Config, title: str, parent=None):
        super().__init__(parent)
        self.config = config
        self.selected_server = None
        self.servers_data = {}  # 保存服务器数据用于刷新状态
        self._status_worker = None
        self.setWindowTitle(title)
        self.setMinimumSize(400, 500)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        
        # 刷新状态按钮
        refresh_layout = QHBoxLayout()
        self.refresh_btn = QPushButton("刷新状态")
        apply_button_style(self.refresh_btn, "outline")
        self.refresh_btn.clicked.connect(self._refresh_status)
        refresh_layout.addWidget(self.refresh_btn)
        
        self.status_label = QLabel("点击刷新状态查看服务器运行情况")
        self.status_label.setStyleSheet("color: #aab4c3;")
        refresh_layout.addWidget(self.status_label)
        refresh_layout.addStretch()
        layout.addLayout(refresh_layout)
        
        # 服务器列表
        self.server_list = QListWidget()
        self.server_list.itemDoubleClicked.connect(self.accept)
        
        self._load_servers()
        
        layout.addWidget(self.server_list)
        
        # 按钮
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)
    
    def _load_servers(self):
        """加载服务器列表"""
        run_dir = self.config.get('workspace', 'run_dir', default='')
        servers = get_server_list(run_dir)
        
        # 获取缓存
        cache = get_node_status_cache()
        
        # 收集所有服务器
        all_servers = []
        for category in ['game', 'cross', 'login', 'client', 'center', 'other']:
            all_servers.extend(servers.get(category, []))
        
        # 添加分类标题和服务器
        categories = [
            ('游戏服务器', servers['game']),
            ('跨服服务器', servers['cross']),
            ('登录服务器', servers['login']),
            ('客户端服务器', servers['client']),
            ('中心服务器', servers['center']),
            ('其他服务器', servers['other'])
        ]
        
        online_count = 0
        total_count = 0
        
        for category, server_list in categories:
            if server_list:
                # 添加分类标题
                title_item = QListWidgetItem(f"--- {category} ---")
                title_item.setFlags(Qt.ItemFlag.NoItemFlags)
                title_item.setForeground(QColor("#25c889"))
                self.server_list.addItem(title_item)
                
                # 添加服务器
                for server in sorted(server_list):
                    # 从缓存读取状态
                    cached_status = cache.get(server)
                    if cached_status is True:
                        status_icon = "🟢"
                        online_count += 1
                    elif cached_status is False:
                        status_icon = "⚪"
                    else:
                        status_icon = "⚪"  # 未缓存，显示未知状态
                    
                    item = QListWidgetItem(f"{status_icon} {server}")
                    item.setData(Qt.ItemDataRole.UserRole, server)
                    if cached_status is True:
                        item.setForeground(QColor("#25c889"))
                    self.server_list.addItem(item)
                    self.servers_data[server] = item
                    total_count += 1
        
        if self.server_list.count() == 0:
            self.server_list.addItem("未找到任何服务器")
        elif total_count > 0:
            self.status_label.setText(f"在线: {online_count}/{total_count}")

        if all_servers and not cache.has_local_nodes(all_servers):
            self.refresh_btn.setEnabled(False)
            self.status_label.setText("正在检查服务器状态...")
            self._start_status_refresh(all_servers, initialize_cache=True)

    def _refresh_status(self):
        """刷新服务器状态（批量检查）"""
        server_names = list(self.servers_data.keys())
        if not server_names:
            return

        self.refresh_btn.setEnabled(False)
        self.status_label.setText("正在检查服务器状态...")
        self._start_status_refresh(server_names)

    def _start_status_refresh(self, server_names, initialize_cache: bool = False):
        """异步刷新服务器状态。"""
        if self._status_worker and self._status_worker.isRunning():
            return

        cookie = self.config.get('server', 'cookie', default='ddxq2-node')
        worker = NodeStatusCheckWorker(
            server_names,
            cookie,
            erl_path=self.config.get('erlang', 'r25_path', default=''),
        )
        self._status_worker = worker
        worker.finished_signal.connect(
            lambda results, init_cache=initialize_cache: self._on_status_refresh_finished(results, init_cache)
        )
        worker.finished.connect(
            lambda w=worker: setattr(self, '_status_worker', None) if self._status_worker is w else None
        )
        worker.finished.connect(worker.deleteLater)
        worker.start()

    def _on_status_refresh_finished(self, results, initialize_cache: bool = False):
        """状态刷新完成后更新界面。"""
        cache = get_node_status_cache()
        cache.batch_set(results)
        if initialize_cache:
            cache.set_initialized(True)

        online_count = 0
        total = len(self.servers_data)
        for server_name, item in self.servers_data.items():
            is_online = results.get(server_name, False)
            if is_online:
                item.setText(f"🟢 {server_name}")
                item.setForeground(QColor("#25c889"))
                online_count += 1
            else:
                item.setText(f"⚪ {server_name}")
                item.setForeground(QColor("#aab4c3"))

        if total > 0:
            self.status_label.setText(f"在线: {online_count}/{total}")
        else:
            self.status_label.setText("未找到任何服务器")
        self.refresh_btn.setEnabled(True)
    
    def accept(self):
        current = self.server_list.currentItem()
        if current:
            self.selected_server = current.data(Qt.ItemDataRole.UserRole)
        super().accept()
