package invalid.lena.rsend

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.concurrent.thread

// LogActivity shows the plain-text sync log with refresh and clear.
class LogActivity : AppCompatActivity() {

    private lateinit var log: TextView
    private var generation = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_log)
        setSupportActionBar(findViewById(R.id.toolbar))
        title = "Log"
        fitSystemBars()
        log = findViewById(R.id.log)
        findViewById<Button>(R.id.refresh).setOnClickListener { load() }
        findViewById<Button>(R.id.clear).setOnClickListener { load(clear = true) }
    }

    override fun onResume() {
        super.onResume()
        load()
    }

    // File I/O stays off the main thread. SyncLog caps displayed text at 64 KB
    // so the unavoidable TextView assignment and layout remain bounded.
    private fun load(clear: Boolean = false) {
        val current = ++generation
        thread {
            val result = try {
                val syncLog = SyncLog(this)
                if (clear) syncLog.clear()
                Result.success(syncLog.text().ifEmpty { "No log yet." })
            } catch (e: Exception) {
                Result.failure(e)
            }
            runOnUiThread {
                if (isFinishing || isDestroyed || current != generation) return@runOnUiThread
                log.text = result.getOrElse { "Could not read log: ${it.message}" }
            }
        }
    }
}
