package com.xd.threadexamplekotlin

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var countButton: Button
    private lateinit var blankButton: Button
    private lateinit var waitButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        countButton = findViewById(R.id.btn_count)
        blankButton = findViewById(R.id.btn_blank)
        waitButton = findViewById(R.id.btn_wait)
    }

    fun startThread(view: View) {
        val countDownThread = Thread(){
            val handler = Handler(Looper.getMainLooper())
            val blankButtonRunnable = Runnable { blankButton.text = "posting from background thread: ${Thread.currentThread().name}" }
            handler.post(blankButtonRunnable)

            var i = 0
            while (i < 1000) {
                try {
                    val countdownButtonRunable = Runnable { countButton.text = "#: $i" }
                    runOnUiThread(countdownButtonRunable)
                    Thread.sleep(80)
                } catch (e: Exception) { }
                i++
            }
        }
        countDownThread.start()
    }

    fun startWaitThread(view: View) {
//        longTask()
        val runLongTask = Runnable { longTask() }
        val thread = Thread(runLongTask)
        thread.start()
    }

    fun longTask() {
        try {
            Thread.sleep(2000)
        } catch (e: java.lang.Exception) { }
    }

}