package com.adealink.weparty.playmate.setting.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.viewmodel.viewModels
import com.adealink.frame.router.Router
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.switchbutton.SwitchButton.OnCheckChangedListener
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.playmate.databinding.LayoutPlaymateOrderSettingSayWelcomeBinding
import com.adealink.weparty.playmate.setting.viewmodel.OrderSettingViewModel
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModelFactory

class OrderSayWelcomeComp(
    lifecycleOwner: LifecycleOwner,
    val binding: LayoutPlaymateOrderSettingSayWelcomeBinding
) : BaseViewComponent(lifecycleOwner) {
    private val viewModel by viewModels<OrderSettingViewModel> { PlaymateViewModelFactory() }

    override fun initViews() {
        super.initViews()
        binding.root.onClick {
            goWelcomeSetting()
        }
        binding.vSwitch.checkChangedListener = object : OnCheckChangedListener {
            override fun onChecked(isChecked: Boolean, fromUser: Boolean) {
                if (fromUser) {
                    switchAutoWelcome(isChecked)
                }
            }
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        viewModel.enableAutoWelcomeLD.observe(viewLifecycleOwner) {
            binding.vSwitch.setChecked(it)
        }
    }

    private fun switchAutoWelcome(enable: Boolean) {
        showLoading()
        viewModel.updateAutoWelcome(enable).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
        }
    }

    private fun goWelcomeSetting() {
        val act = activity ?: return
        Router.build(act, Playmate.SayWelcome.PATH).start()
    }
}