package com.dong.demo013

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

@OptIn(DelicateCoroutinesApi::class)
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
    }

}

actual fun pirntSingleHiLog(){
    hiLogPrintMsg(0u, 6u, 4660u, "TestTag", "单次日志打印");

}

actual fun pirntAllLevelHiLog(){
// 输出 DEBUG 级别
    // LOG_APP = 0 (应用日志类型)
    // LOG_DEBUG = 3 (调试级别)
    // domain = 0x1234 (任意自定义值，范围0x0000-0xFFFF)
    // tag = "TestTag" (自定义标签)
    hiLogPrintMsg(0u, 3u, 4660u, "TestTag", "This is a DEBUG log from PrintMsg");

    // 输出 INFO 级别
    // LOG_INFO = 4 (信息级别)
    hiLogPrintMsg(0u, 4u, 4660u, "TestTag", "This is an INFO log from PrintMsg");

    // 输出 WARN 级别
    // LOG_WARN = 5 (警告级别)
    hiLogPrintMsg(0u, 5u, 4660u, "TestTag", "This is a WARN log from PrintMsg");

    // 输出 ERROR 级别
    // LOG_ERROR = 6 (错误级别)
    hiLogPrintMsg(0u, 6u, 4660u, "TestTag", "This is an ERROR log from PrintMsg");

    // 输出 FATAL 级别
    // LOG_FATAL = 7 (致命级别)
    hiLogPrintMsg(0u, 7u, 4660u, "TestTag", "This is a FATAL log from PrintMsg");
}
