package com.dong.demo013

import com.dong.test1.TimerControllerImpl
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import platform.PerformanceAnalysisKit.HiLog.OH_LOG_PrintMsg

actual fun startLog(
    speed: Int,
    onLogGenerated: ((Int) -> Unit)?,
    onTimerUpdated: ((Long) -> Unit)?
): LogController {
    val controller = LogControllerImpl()
    // 启动协程在后台执行日志生成
    GlobalScope.launch {
        generateLogs(speed, onLogGenerated, onTimerUpdated, controller)
    }
    return controller
}

actual fun createTimer(): TimerController {
    return TimerControllerImpl()
}

private suspend fun generateLogs(speed: Int, onLogGenerated: ((Int) -> Unit)?, onTimerUpdated: ((Long) -> Unit)?, controller: LogControllerImpl) {
    val startTime = getTimeMillis()
    var count = 0

    // 发送开始日志 (fatal级别)
    hiLogPrintMsg(
        type = 0u,
        level = 4u, // FATAL level
        domain = 0x1234u,
        tag = "LogGenerator",
        message = "日志生成开始，间隔 ${speed} 毫秒，手动停止模式"
    )

    // 手动停止模式：持续运行直到用户停止
    while (controller.isRunning) {
        val currentTime = getTimeMillis()
        val elapsedSeconds = (currentTime - startTime) / 1000

        // 每秒更新一次计时器显示
        if (elapsedSeconds > count) {
            onTimerUpdated?.invoke(elapsedSeconds)
        }

        // 发送普通info日志
        hiLogPrintMsg(
            type = 0u,
            level = 1u, // INFO level
            domain = 0x1234u,
            tag = "LogGenerator",
            message = "生成第 ${++count} 条日志，运行时间: $elapsedSeconds 秒"
        )

        // 通知UI更新计数
        onLogGenerated?.invoke(count)

        // 等待指定间隔
        kotlinx.coroutines.delay(speed.toLong())
    }

    // 发送结束日志
    val finalTime = (getTimeMillis() - startTime) / 1000
    hiLogPrintMsg(
        type = 0u,
        level = 4u, // FATAL level
        domain = 0x1234u,
        tag = "LogGenerator",
        message = "日志生成手动停止，总运行时间: $finalTime 秒，总共生成: $count 条日志"
    )
}

// 获取当前时间戳（毫秒）
private fun getTimeMillis(): Long {
    return kotlin.time.TimeSource.Monotonic.markNow().elapsedNow().inWholeMilliseconds
}

@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class, kotlin.experimental.ExperimentalNativeApi::class)
@CName("hiLogPrintMsg")
fun hiLogPrintMsg(type: UInt, level: UInt, domain: UInt, tag: String, message: String): Int {
    return try {
        OH_LOG_PrintMsg(type, level, domain, tag, message)
    } catch (_: Throwable) {
        -1
    }

}