package com.example.cmake_project_test

import android.util.Log
import type.SensorData
import java.util.*

/**
 * 指标计算器 - 负责计算各种生理指标
 * 处理流程：原始数据 → 解析数据 → 通道映射 → 信号处理 → 指标计算
 */
class IndicatorCalculator {
    
    companion object {
        // 加载本地库
        init {
            System.loadLibrary("cmake_project_test")
        }
    }
    
    // 本地计算器句柄
    private var calculatorHandle: Long = 0
    
    /**
     * 初始化指标计算器
     */
    fun initialize(): Boolean {
        try {
            calculatorHandle = createIndicatorCalculator()
            if (calculatorHandle != 0L) {
                Log.d("IndicatorCalculator", "指标计算器初始化成功，句柄: $calculatorHandle")
                return true
            } else {
                Log.e("IndicatorCalculator", "指标计算器初始化失败")
                return false
            }
        } catch (e: Exception) {
            Log.e("IndicatorCalculator", "初始化指标计算器时发生错误: ${e.message}")
            return false
        }
    }
    
    /**
     * 完整数据处理流程
     * 输入原始数据，输出所有计算的指标
     */
    fun processCompletePipeline(sensorData: SensorData, sampleRate: Float): Map<String, Float>? {
        if (calculatorHandle == 0L) {
            Log.w("IndicatorCalculator", "指标计算器未初始化")
            return null
        }
        
        return try {
            val metrics = processCompletePipeline(calculatorHandle, sensorData, sampleRate)
            if (metrics != null) {
                Log.d("IndicatorCalculator", "完整数据处理流程完成，计算了 ${metrics.size} 个指标")
                metrics
            } else {
                Log.w("IndicatorCalculator", "完整数据处理流程失败")
                null
            }
        } catch (e: Exception) {
            Log.e("IndicatorCalculator", "完整数据处理流程时发生错误: ${e.message}")
            null
        }
    }
    
    /**
     * 计算ECG指标
     */
    fun calculateECGMetrics(sensorData: SensorData, sampleRate: Float): Map<String, Float>? {
        if (calculatorHandle == 0L) {
            Log.w("IndicatorCalculator", "指标计算器未初始化")
            return null
        }
        
        return try {
            val metrics = calculateECGMetrics(calculatorHandle, sensorData, sampleRate)
            if (metrics != null) {
                Log.d("IndicatorCalculator", "ECG指标计算完成，计算了 ${metrics.size} 个指标")
                metrics
            } else {
                Log.w("IndicatorCalculator", "ECG指标计算失败")
                null
            }
        } catch (e: Exception) {
            Log.e("IndicatorCalculator", "ECG指标计算时发生错误: ${e.message}")
            null
        }
    }
    
    /**
     * 计算PPG指标
     */
    fun calculatePPGMetrics(sensorData: SensorData, sampleRate: Float): Map<String, Float>? {
        if (calculatorHandle == 0L) {
            Log.w("IndicatorCalculator", "指标计算器未初始化")
            return null
        }
        
        return try {
            val metrics = calculatePPGMetrics(calculatorHandle, sensorData, sampleRate)
            if (metrics != null) {
                Log.d("IndicatorCalculator", "PPG指标计算完成，计算了 ${metrics.size} 个指标")
                metrics
            } else {
                Log.w("IndicatorCalculator", "PPG指标计算失败")
                null
            }
        } catch (e: Exception) {
            Log.e("IndicatorCalculator", "PPG指标计算时发生错误: ${e.message}")
            null
        }
    }
    
    /**
     * 计算HRV指标
     */
    fun calculateHRVMetrics(rrIntervals: List<Float>): Map<String, Float>? {
        if (calculatorHandle == 0L) {
            Log.w("IndicatorCalculator", "指标计算器未初始化")
            return null
        }
        
        return try {
            val metrics = calculateHRVMetrics(calculatorHandle, rrIntervals)
            if (metrics != null) {
                Log.d("IndicatorCalculator", "HRV指标计算完成，计算了 ${metrics.size} 个指标")
                metrics
            } else {
                Log.w("IndicatorCalculator", "HRV指标计算失败")
                null
            }
        } catch (e: Exception) {
            Log.e("IndicatorCalculator", "HRV指标计算时发生错误: ${e.message}")
            null
        }
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        if (calculatorHandle != 0L) {
            try {
                destroyIndicatorCalculator(calculatorHandle)
                calculatorHandle = 0L
                Log.d("IndicatorCalculator", "指标计算器资源已清理")
            } catch (e: Exception) {
                Log.e("IndicatorCalculator", "清理指标计算器资源时发生错误: ${e.message}")
            }
        }
    }
    
    /**
     * 检查计算器是否已初始化
     */
    fun isInitialized(): Boolean = calculatorHandle != 0L
    
    // ============================================================================
    // JNI函数声明
    // ============================================================================
    
    /**
     * 创建指标计算器实例
     * @return 计算器句柄，0表示失败
     */
    private external fun createIndicatorCalculator(): Long
    
    /**
     * 销毁指标计算器实例
     * @param calculatorHandle 计算器句柄
     */
    private external fun destroyIndicatorCalculator(calculatorHandle: Long)
    
    /**
     * 完整数据处理流程
     * @param calculatorHandle 计算器句柄
     * @param sensorData 传感器数据
     * @param sampleRate 采样率
     * @return 计算的指标映射，null表示失败
     */
    private external fun processCompletePipeline(calculatorHandle: Long, sensorData: SensorData, sampleRate: Float): Map<String, Float>?
    
    /**
     * 计算ECG指标
     * @param calculatorHandle 计算器句柄
     * @param sensorData 传感器数据
     * @param sampleRate 采样率
     * @return 计算的ECG指标映射，null表示失败
     */
    private external fun calculateECGMetrics(calculatorHandle: Long, sensorData: SensorData, sampleRate: Float): Map<String, Float>?
    
    /**
     * 计算PPG指标
     * @param calculatorHandle 计算器句柄
     * @param sensorData 传感器数据
     * @param sampleRate 采样率
     * @return 计算的PPG指标映射，null表示失败
     */
    private external fun calculatePPGMetrics(calculatorHandle: Long, sensorData: SensorData, sampleRate: Float): Map<String, Float>?
    
    /**
     * 计算HRV指标
     * @param calculatorHandle 计算器句柄
     * @param rrIntervals RR间期列表
     * @return 计算的HRV指标映射，null表示失败
     */
    private external fun calculateHRVMetrics(calculatorHandle: Long, rrIntervals: List<Float>): Map<String, Float>?
}
