package com.mxn.helper.screenshot

import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.KeyEvent
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mxn.helper.screenshot.logcat.LogcatReader
import com.mxn.helper.screenshot.logcat.MyAdapter

class LogcatActivity : AppCompatActivity() {
    private var recyclerView: RecyclerView? = null
    private var adapter: MyAdapter? = null
    private var list: MutableList<String>? = null
    private var thread: Thread? = null
    private var tvLog: TextView? = null
    private var handler:Handler? = null

    private var localData: MutableList<String>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_logcat)
        recyclerView = findViewById(R.id.recycler_view)
        tvLog = findViewById(R.id.tv_log)

        list = mutableListOf()
        localData = mutableListOf()
        adapter = MyAdapter(list)
        val layoutManager = LinearLayoutManager(this)
        recyclerView?.layoutManager = layoutManager
        recyclerView?.adapter = adapter

        val logcatReader = LogcatReader {
            runOnUiThread {
                kotlin.runCatching {
                    tvLog?.text = it
                    addData(it)
                }
            }
        }
        thread = Thread(logcatReader)
        thread?.start()

        handler = Handler()
    }

    /***
     * 添加数据
     */
    @Synchronized
    public fun addData(msg: String) {
        localData?.add(msg)

        if (localData?.size == 4) {
            notifyData()
        }
    }

    @Synchronized
    fun notifyData() {
        handler?.post(Runnable {
            list?.addAll(localData ?: mutableListOf())
            localData?.clear()
            adapter?.notifyDataSetChanged()
            recyclerView?.scrollToPosition((list?.size ?: 0) - 1)
        })
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (event?.action == KeyEvent.ACTION_DOWN) {
            Log.e("HHHHHH", "" + System.currentTimeMillis() + " 哈哈")
        }
        return super.dispatchKeyEvent(event)
    }

    override fun onDestroy() {
        super.onDestroy()
        thread?.stop()
    }
}