package six.ca.androidadvanced.architecture.coroutines

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.act_coroutine.*
import six.ca.androidadvanced.R

/**
 * @author hellenxu
 * @date 2019-05-29
 * Copyright 2019 Six. All rights reserved.
 */
class MainSample: AppCompatActivity(), View.OnClickListener {
    private lateinit var userViewModel: UserViewModel

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

        btnGetUser.setOnClickListener(this)
        userViewModel = ViewModelProvider.NewInstanceFactory().create(UserViewModel::class.java)
    }

    override fun onClick(v: View?) {
        tvResult.text = getString(R.string.loading)
        userViewModel.getUserList()
        userViewModel.userList.observe(::getLifecycle, ::updateContent)
    }

    private fun updateContent(result: List<User>) {
        val sb = StringBuilder()
        result.forEach {
            sb.append(it.toString()).append(System.lineSeparator())
        }
        tvResult.text = sb.toString()
    }
}