//
//  ConnectionState.swift
//  otg_swift
//
//  Created by hanqiu on 2026/7/2.
//

import Foundation

/// OTG 连接流程的状态机，供 ViewModel 绑定 `displayText` 展示给用户。
enum ConnectionState: Equatable {
    /// 初始态，尚未开始搜索或已完全复位
    case idle
    /// 正在通过 ICDeviceBrowser 发现 USB 相机
    case searching
    /// 已发现设备，正在打开 Session 或等待系统授权
    case connecting(deviceName: String)
    /// Session 已打开且 Driver 已创建；`platform` 用于品牌相关 UI 提示
    case connected(platform: CameraPlatform, deviceName: String)
    /// 用户主动断开或 Session 已关闭，设备仍可能插在 USB 上
    case disconnected
    /// 授权被拒、不支持品牌或 Session 打开失败；`message` 为可读错误说明
    case failed(message: String)
}

extension ConnectionState: CustomStringConvertible {
    var description: String {
        switch self {
        case .idle: return "idle"
        case .searching: return "searching"
        case .connecting(let name): return "connecting(\(name))"
        case .connected(let platform, let name):
            return "connected(\(platform.rawValue), \(name))"
        case .disconnected: return "disconnected"
        case .failed(let message): return "failed(\(message))"
        }
    }

    var displayText: String {
        switch self {
        case .idle: return "等待开始"
        case .searching: return "正在搜索相机…"
        case .connecting(let name): return "正在连接 \(name)…"
        case .connected(let platform, let name):
            return "已连接 \(platformLabel(platform)) · \(name)"
        case .disconnected: return "已断开连接"
        case .failed(let msg): return "连接失败：\(msg)"
        }
    }
    private func platformLabel(_ platform: CameraPlatform) -> String {
        switch platform {
        case .nikon: return "尼康"
        case .canon: return "佳能"
        case .sony: return "索尼"
        case .unknown: return "未知"
        }
    }
}
