package com.xd.countdowntaskkotlin

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main

class MainActivity : AppCompatActivity() {
    private lateinit var textView1: TextView
    private lateinit var textView2: TextView
    private lateinit var textView3: TextView

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

        textView1 = findViewById(R.id.text_view1)
        textView1.text = "hello world"
        textView2 = findViewById(R.id.text_view2)
        textView3 = findViewById(R.id.text_view3)


        CoroutineScope(IO).launch{
            countDownTask()
            countDownTaskJob() //anything inside this function will be executed after the completion of countDownTask()
        }
        textView1.text = "*START*"
    }

    private suspend fun countDownTask(){
        for (i in 15 downTo 0) {
            delay(800)
//            textView1.text = i.toString() //app crashes
            setTextOnMainThread(textView1, i.toString())
        }
        setTextOnMainThread(textView1,"*DONE*")
    }

    private suspend fun setTextOnMainThread(tv: TextView, input: String){
        withContext(Main){
            tv.text = input
        }
    }

    private suspend fun countDownTaskJob(){
        withContext(IO){
            var job1 = launch{
                for (i in 0 .. 15) {
                    delay(800)
                    setTextOnMainThread(textView2, i.toString())
                }
                setTextOnMainThread(textView2, "*DONE*")
            }
            job1.join() //this forces job2 to be executed after job1
            var job2 = launch{
                for (i in 0 .. 15) {
                    delay(800)
                    setTextOnMainThread(textView3, i.toString())
                }
            }
            setTextOnMainThread(textView3, "*DONE*") //this line will be executed before the i=0 is shown

        }
    }
}