package com.example.cmake_project_test

import android.util.Log
import type.SensorData
import java.util.concurrent.atomic.AtomicBoolean

/**
 * UI管理类
 * 负责UI更新、统计信息构建和显示逻辑
 */
class UiManager {
    
    private val uiUpdatePending = AtomicBoolean(false)
    private var lastUpdateTime = 0L
    
    /**
     * 计划UI更新，避免频繁刷新
     */
    fun scheduleUiUpdate(
        dataManager: DataManager,
        updateCallback: () -> Unit
    ) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastUpdateTime >= Constants.UPDATE_INTERVAL && 
            uiUpdatePending.compareAndSet(false, true)) {
            lastUpdateTime = currentTime
            updateCallback()
            uiUpdatePending.set(false)
        }
    }
    
    /**
     * 构建统计信息字符串
     */
    fun buildStatisticsString(dataManager: DataManager): String {
        return try {
            val packetBuffer = dataManager.getPacketBuffer()
            
            buildString {
                append("=== 设备数据概览 ===\n")
                append("当前缓冲区: ${dataManager.getPacketBufferSize()} 个数据包\n")
                append("总共解析: ${dataManager.getTotalPacketsParsed()} 个数据包\n")
                append("总数据量: ${dataManager.getRawStreamSize()} 字节\n")
                
                if (packetBuffer.isNotEmpty()) {
                    // 获取设备类型信息
                    val deviceTypes = packetBuffer.mapNotNull { it.dataType }.distinct()
                    val deviceInfo = deviceTypes.joinToString(", ") { DeviceTypeHelper.getDeviceName(it) }
                    append("设备类型: $deviceInfo\n")
                } else {
                    append("设备类型: 无\n")
                }
                
                append("\n")
            }
        } catch (e: Exception) {
            Log.e("UiManager", "构建统计信息失败: ${e.message}", e)
            "=== 设备数据概览 ===\n构建统计信息失败: ${e.message}\n\n"
        }
    }
    
    /**
     * 构建完整的显示内容
     */
    fun buildDisplayContent(dataManager: DataManager): String {
        return try {
            val packetBuffer = dataManager.getPacketBuffer()
            val processedPackets = dataManager.getProcessedPackets()
            val calculatedMetrics = dataManager.getCalculatedMetrics()
            
            // 即使没有数据，也显示基本状态信息
            val stats = buildStatisticsString(dataManager)
            
            if (packetBuffer.isEmpty()) {
                return stats + "\n\n暂无数据包详情\n\n正在加载数据文件，请稍候..."
            }
            
            // 构建信号处理信息
            val signalProcessingInfo = buildSignalProcessingInfo(dataManager, processedPackets)
            
            // 构建指标计算信息
            val metricsInfo = buildMetricsInfo(calculatedMetrics)
            
            // 只显示最新的一些数据包详情
            val recentPackets = packetBuffer.takeLast(Constants.MAX_DISPLAY_PACKETS)
            val has12Lead = recentPackets.any { it.dataType == SensorData.DataType.ECG_12LEAD }
            
            val channelDetails = if (has12Lead) {
                DeviceTypeHelper.buildChannelDetails(
                    recentPackets, 
                    maxPackets = Constants.MAX_DETAIL_PACKETS, 
                    maxChannels = Constants.MAX_12LEAD_CHANNELS, 
                    maxSamples = Constants.MAX_DISPLAY_SAMPLES
                )
            } else {
                DeviceTypeHelper.buildChannelDetails(
                    recentPackets, 
                    maxPackets = Constants.MAX_DETAIL_PACKETS, 
                    maxChannels = Constants.MAX_DISPLAY_CHANNELS, 
                    maxSamples = Constants.MAX_DISPLAY_SAMPLES
                )
            }
            
            stats + signalProcessingInfo + metricsInfo + channelDetails
        } catch (e: Exception) {
            Log.e("UiManager", "构建显示内容时发生错误: ${e.message}", e)
            "构建显示内容时发生错误: ${e.message}\n\n请检查数据格式是否正确。"
        }
    }
    
    /**
     * 构建信号处理信息
     */
    private fun buildSignalProcessingInfo(dataManager: DataManager, processedPackets: List<SensorData>): String {
        return buildString {
            append("\n=== 信号处理信息 ===\n")
            
            if (processedPackets.isEmpty()) {
                append("暂无信号处理数据\n")
            } else {
                append("已处理数据包: ${processedPackets.size} 个\n")
                
                // 显示流式信号处理器状态
                val bufferStatus = dataManager.getStreamingSignalProcessorStatus()
                if (bufferStatus.isNotEmpty()) {
                    append("\n流式处理器状态:\n")
                    bufferStatus.forEach { (key, value) ->
                        append("- $key: $value\n")
                    }
                }
                
                // 显示最新处理的数据包信息
                val latestPacket = processedPackets.lastOrNull()
                if (latestPacket != null) {
                    append("\n最新处理数据包:\n")
                    append("- 数据类型: ${DeviceTypeHelper.getDeviceName(latestPacket.getDataType())}\n")
                    append("- 时间戳: ${latestPacket.getTimestamp()}\n")
                    append("- 包序号: ${latestPacket.getPacketSn()}\n")
                    
                    val channelData = latestPacket.getChannelData()
                    if (channelData != null && channelData.isNotEmpty()) {
                        append("- 通道数: ${channelData.size}\n")
                        channelData.forEachIndexed { index, channel ->
                            if (channel != null) {
                                append("- 通道${index + 1}样本数: ${channel.size}\n")
                            } else {
                                append("- 通道${index + 1}: 空数据\n")
                            }
                        }
                    }
                }
            }
            
            append("\n")
        }
    }
    
    /**
     * 构建指标计算信息
     */
    private fun buildMetricsInfo(calculatedMetrics: List<Map<String, Float>>): String {
        return buildString {
            append("\n=== 指标计算信息 ===\n")
            
            if (calculatedMetrics.isEmpty()) {
                append("暂无指标数据\n")
                append("可能的原因:\n")
                append("- 指标计算器未初始化\n")
                append("- 数据处理流程未执行\n")
                append("- 指标计算返回空结果\n")
            } else {
                append("已计算 ${calculatedMetrics.size} 个数据包的指标\n")
                append("非空指标数: ${calculatedMetrics.count { it.isNotEmpty() }}\n")
                
                // 显示最新一个数据包的指标
                val latestMetrics = calculatedMetrics.lastOrNull()
                if (latestMetrics != null && latestMetrics.isNotEmpty()) {
                    append("\n最新指标:\n")
                    for ((key, value) in latestMetrics) {
                        val formattedValue = when {
                            key.contains("rate") || key.contains("hr") -> String.format("%.1f bpm", value)
                            key.contains("spo2") -> String.format("%.1f%%", value)
                            key.contains("quality") -> String.format("%.2f", value)
                            key.contains("amplitude") || key.contains("offset") -> String.format("%.3f mV", value)
                            key.contains("width") -> String.format("%.1f ms", value)
                            key.contains("timestamp") || key.contains("packet_sn") || key.contains("data_type") -> String.format("%.0f", value)
                            else -> String.format("%.3f", value)
                        }
                        append("- $key: $formattedValue\n")
                    }
                } else {
                    append("最新指标: 无数据\n")
                }
                
                // 显示统计信息
                if (calculatedMetrics.size > 1) {
                    val allHeartRates = calculatedMetrics.mapNotNull { it["heart_rate"] }.filter { it > 0 }
                    val allQualities = calculatedMetrics.mapNotNull { it["signal_quality"] }.filter { it >= 0 }
                    
                    if (allHeartRates.isNotEmpty()) {
                        val avgHeartRate = allHeartRates.average()
                        append("\n平均心率: ${String.format("%.1f", avgHeartRate)} bpm\n")
                    }
                    
                    if (allQualities.isNotEmpty()) {
                        val avgQuality = allQualities.average()
                        append("平均信号质量: ${String.format("%.2f", avgQuality)}\n")
                    }
                }
            }
            
            append("\n")
        }
    }
    
    /**
     * 更新UI显示内容
     */
    fun updateDisplay(
        dataManager: DataManager,
        updateTextCallback: (String) -> Unit
    ) {
        val displayContent = buildDisplayContent(dataManager)
        updateTextCallback(displayContent)
        
        // 智能清理缓冲区
        dataManager.cleanupBuffer()
        
        // 添加调试信息
        Log.d("UiManager", "当前缓冲区数据包数量: ${dataManager.getPacketBufferSize()}, 总共解析: ${dataManager.getTotalPacketsParsed()}")
    }
}
