import json
import os

class ConfigManager:
    """配置管理器"""
    def __init__(self, config_file='config.json'):
        self.config_file = config_file
        self.default_config = {
            "groups": [
                {
                    "name": "配置组1",
                    "serial_port": "COM6",
                    "serial_baudrate": 9600,
                    "camera_index": 0,
                    "camera_width": 1920,
                    "camera_height": 1080,
                    "move_velocity": 470,
                    "active": False
                }
            ],
            "display": {
                "preview_window_width": 640,
                "preview_window_height": 360,
                "preview_columns": 2,
                "preview_rows": 2,
                "show_preview": True
            }
        }
        self.config = self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 确保有默认结构
                    if 'groups' not in config:
                        config['groups'] = self.default_config['groups']
                    if 'display' not in config:
                        config['display'] = self.default_config['display']
                    return config
            except Exception as e:
                print(f"加载配置文件失败: {e}")
                return self.default_config.copy()
        return self.default_config.copy()
    
    def save_config(self):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=4)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False
    
    def add_group(self, name=None):
        """添加配置组"""
        if name is None:
            name = f"配置组{len(self.config['groups']) + 1}"
        
        new_group = {
            "name": name,
            "serial_port": "COM6",
            "serial_baudrate": 9600,
            "camera_index": len(self.config['groups']),
            "camera_width": 1920,
            "camera_height": 1080,
            "move_velocity": 470,
            "active": False
        }
        self.config['groups'].append(new_group)
        return new_group
    
    def delete_group(self, index):
        """删除配置组"""
        if 0 <= index < len(self.config['groups']):
            del self.config['groups'][index]
            return True
        return False
    
    def update_group(self, index, **kwargs):
        """更新配置组"""
        if 0 <= index < len(self.config['groups']):
            self.config['groups'][index].update(kwargs)
            return True
        return False
    
    def get_active_group(self):
        """获取当前活动的配置组"""
        for group in self.config['groups']:
            if group.get('active', False):
                return group
        return None
    
    def set_active_group(self, index):
        """设置活动的配置组"""
        for i, group in enumerate(self.config['groups']):
            group['active'] = (i == index)
        return True
    
    def get_group_by_index(self, index):
        """根据索引获取配置组"""
        if 0 <= index < len(self.config['groups']):
            return self.config['groups'][index]
        return None

# 全局配置管理器实例
config_manager = ConfigManager()

