package com.xd.listviewofprofskotlin

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.ArrayList

class MainActivity : AppCompatActivity() {
    private val items = arrayOf(
            "Chris Bailey-Kellogg",
            "Devin Balkcom", "Andrew Campbell", "Michael Casey",
            "Amit Chakrabarti", "Thomas H. Cormen ",
            "Robert L. (Scot) Drysdale, III", "Hany Farid", "Lisa Fleischer",
            "Gevorg Grigoryan", "Prasad Jayanti", "David Kotz", "Lorie Loeb",
            "Fabio Pellacini", "Daniel Rockmore", "Sean Smith",
            "Lorenzo Torresani", "Peter Winkler", "Emily Whiting", "Xia Zhou"
    )
    private lateinit var arrayList: ArrayList<String>
    private lateinit var arrayAdapter: ArrayAdapter<String>
    private lateinit var myListView: ListView

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

        myListView = findViewById(R.id.myListView)
        arrayList = ArrayList()
        arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList)
        myListView.adapter = arrayAdapter

        CoroutineScope(IO).launch {
            for(item in items){
                delay(1000)
//                showProfNameOnMainThread(item)
                arrayList.add(item)
                val list = ArrayList<String>(arrayList) //XD: we should not just pass arrayList reference as a parameter of showProfNameOnMainThread() because down there arrayAdapter.clear() will remove everything inside the arrayList. So we create a copy of the arrayList
                showProfNameOnMainThread(list)
            }
        }
    }

    private suspend fun showProfNameOnMainThread(arrayList: ArrayList<String>){
        withContext(Main){
            arrayAdapter.clear()
            arrayAdapter.addAll(arrayList)
            arrayAdapter.notifyDataSetChanged()
        }
    }

//    private suspend fun showProfNameOnMainThread(profName: String){
//        withContext(Main){
//            arrayAdapter.add(profName)
//        }
//    }


}