package com.example.m20_gamepad.service

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * ICMP 延迟监测器。使用系统 ping 命令测量到目标主机的往返延迟。
 *
 * @param host 目标主机 IP
 * @param intervalMs 测量间隔（毫秒）
 * @param scope 协程作用域
 */
class PingMonitor(
    private val host: String,
    private val intervalMs: Long = 3000L,
    private val scope: CoroutineScope
) {
    private val _latencyMs = MutableStateFlow<Long?>(null)
    val latencyMs: StateFlow<Long?> = _latencyMs.asStateFlow()

    private var job: Job? = null

    fun start() {
        stop()
        job = scope.launch {
            while (isActive) {
                _latencyMs.value = ping()
                delay(intervalMs)
            }
        }
    }

    fun stop() {
        job?.cancel()
        job = null
        _latencyMs.value = null
    }

    /**
     * 执行一次 ICMP ping，返回延迟毫秒数；失败返回 null。
     */
    private fun ping(): Long? {
        return try {
            val process = ProcessBuilder(
                "ping", "-c", "1", "-W", "2", host
            ).redirectErrorStream(true).start()

            val reader = BufferedReader(InputStreamReader(process.inputStream))
            val output = reader.readText()
            process.waitFor()

            // 解析 "time=12.3 ms" 格式
            val regex = Regex("time=(\\d+(?:\\.\\d+)?)\\s*ms")
            val match = regex.find(output)
            match?.groupValues?.get(1)?.toDouble()?.toLong()
        } catch (_: Exception) {
            null
        }
    }
}
