package com.xd.binddemokotlin

import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class MyViewModel : ViewModel(), ServiceConnection {
    private var myMessageHandler: MyMessageHandler
    private val _counter = MutableLiveData<Int>()
    val counter: LiveData<Int>
        get() {
            return _counter
        }

    init {
        myMessageHandler = MyMessageHandler(Looper.getMainLooper())
    }

    override fun onServiceConnected(name: ComponentName, iBinder: IBinder) {
        println("debug: ViewModel: onServiceConnected() called; ComponentName: $name")
        val tempBinder = iBinder as CounterService.MyBinder
        tempBinder.setmsgHandler(myMessageHandler)
    }

    override fun onServiceDisconnected(name: ComponentName) {
        println("debug: Activity: onServiceDisconnected() called~~~")
    }

    inner class MyMessageHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            if (msg.what == CounterService.MSG_INT_VALUE) {
                val bundle = msg.data
                _counter.value = bundle.getInt(CounterService.INT_KEY)
            }
        }
    }

}