package com.system.cloudservice.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ScrollView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.system.cloudservice.R
import com.system.cloudservice.util.Logger
import kotlinx.coroutines.*

class LogFragment : Fragment() {

    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var refreshJob: Job? = null
    private val maxLines = 500

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        view.findViewById<Button>(R.id.btnClearLog).setOnClickListener {
            Logger.clearBuffer()
            view.findViewById<TextView>(R.id.tvLogContent).text = "日志已清空"
        }
        refreshLog(view)
    }

    override fun onResume() {
        super.onResume()
        refreshJob = scope.launch {
            while (isActive) {
                view?.let { refreshLog(it) }
                delay(2000)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        refreshJob?.cancel()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        scope.cancel()
    }

    private fun refreshLog(view: View) {
        val logs = Logger.getRecentLogs(maxLines)
        val content = if (logs.isEmpty()) {
            "暂无日志...\n\n提示：当设备连接服务器并执行任务时，日志将实时显示在此处。"
        } else {
            logs.joinToString("\n")
        }
        view.findViewById<TextView>(R.id.tvLogContent).text = content
        val scrollView = view.findViewById<ScrollView>(R.id.logScrollView)
        scrollView.post { scrollView.fullScroll(ScrollView.FOCUS_DOWN) }
    }
}
