/**
 * HomeFragment.kt
 * SkyLink Android - 首页片段
 *
 * 显示视频、GPS 和统计信息
 *
 * @author flowzl
 * @date 2026-01-19
 */

package com.skylink.app.ui

import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.skylink.app.R
import com.skylink.app.network.DecodedFrame
import com.skylink.app.network.UdpReceiver
import com.skylink.app.network.UdpReceiverListener
import com.skylink.app.utils.BitmapUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.*

class HomeFragment : Fragment(), UdpReceiverListener {

    companion object {
        private const val TAG = "HomeFragment"
    }

    // ========================================================================
    // UI 组件
    // ========================================================================

    private var videoImageView: ImageView? = null
    private var gpsTextView: TextView? = null
    private var statsTextView: TextView? = null
    private var statusTextView: TextView? = null
    private var saveButton: Button? = null
    private var recordButton: Button? = null

    // ========================================================================
    // 业务逻辑
    // ========================================================================

    private var udpReceiver: UdpReceiver? = null
    private var currentFrame: DecodedFrame? = null
    private var isRecording = false

    // ========================================================================
    // 生命周期方法
    // ========================================================================

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initUI(view)
        startUdpReceiver()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        stopUdpReceiver()
    }

    // ========================================================================
    // UI 初始化
    // ========================================================================

    private fun initUI(view: View) {
        videoImageView = view.findViewById(R.id.video_image)
        gpsTextView = view.findViewById(R.id.gps_text)
        statsTextView = view.findViewById(R.id.stats_text)
        statusTextView = view.findViewById(R.id.status_text)
        saveButton = view.findViewById(R.id.save_button)
        recordButton = view.findViewById(R.id.record_button)

        // 设置按钮点击监听
        saveButton?.setOnClickListener {
            onSaveFrameClicked()
        }

        recordButton?.setOnClickListener {
            onRecordToggled()
        }
    }

    // ========================================================================
    // UDP 接收器管理
    // ========================================================================

    private fun startUdpReceiver() {
        if (udpReceiver == null) {
            udpReceiver = UdpReceiver(listenPort = 9999, listener = this)
            udpReceiver?.start()
            updateStatus("接收器已启动，等待数据...")
        }
    }

    private fun stopUdpReceiver() {
        udpReceiver?.stop()
        udpReceiver = null
    }

    // ========================================================================
    // UDP 接收器回调
    // ========================================================================

    override fun onFrameDecoded(frame: DecodedFrame) {
        currentFrame = frame

        // 移到后台线程执行解码，避免阻塞 UI 线程，进而影响 UDP 接收协程（如果是单核或高负载）
        lifecycleScope.launch(Dispatchers.Default) {
             val bitmap = BitmapUtils.decodeBitmap(frame.imageData)
             if (bitmap != null) {
                 withContext(Dispatchers.Main) {
                     view?.let {
                         videoImageView?.setImageBitmap(bitmap)
                         updateGpsInfo(frame)
                     }
                 }
             }
        }
    }

    override fun onStatsUpdated(fps: Int, kbps: Int, packetLoss: Double) {
        statsTextView?.text = String.format(
            "FPS: %d\nSpeed: %d KB/s\nPacket Loss: %.1f%%",
            fps, kbps, packetLoss
        )
    }

    override fun onError(message: String, exception: Exception?) {
        view?.let {
            Toast.makeText(context, "错误: $message", Toast.LENGTH_SHORT).show()
            updateStatus("❌ $message")
        }
    }

    // ========================================================================
    // UI 事件处理
    // ========================================================================

    private fun onSaveFrameClicked() {
        val frame = currentFrame
        if (frame != null) {
            val bitmap = BitmapUtils.decodeBitmap(frame.imageData)
            if (bitmap != null) {
                // 这里可以保存到文件系统
                Toast.makeText(context, "帧已保存", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(context, "还没有接收到图像", Toast.LENGTH_SHORT).show()
        }
    }

    private fun onRecordToggled() {
        isRecording = !isRecording
        recordButton?.text = if (isRecording) "⏹ 停止录制" else "⏺ 开始录制"
        updateStatus(if (isRecording) "正在录制..." else "录制已停止")
    }

    // ========================================================================
    // 信息更新
    // ========================================================================

    private fun updateGpsInfo(frame: DecodedFrame) {
        gpsTextView?.text = String.format(
            "Latitude: %.6f°\nLongitude: %.6f°\nAltitude: %.1f m\nTime: %s",
            frame.lat,
            frame.lon,
            frame.alt,
            getTimeString(frame.timestamp)
        )
    }

    private fun updateStatus(message: String) {
        statusTextView?.text = message
    }

    private fun getTimeString(timestamp: Double): String {
        val millis = timestamp.toLong() * 1000
        val formatter = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        return formatter.format(Date(millis))
    }
}
