package com.adealink.weparty.profile.dialog

import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.commonui.widget.EvaluateView
import com.adealink.weparty.module.profile.data.UserInfo
import com.adealink.weparty.profile.R
import com.adealink.weparty.profile.databinding.DialogPlaymateCharmStarBinding
import com.adealink.weparty.profile.dialog.viewmodel.PlaymateCharmStarViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModelFactory

class CharmStarDialog : BottomDialogFragment(R.layout.dialog_playmate_charm_star) {

    private val binding by viewBinding(DialogPlaymateCharmStarBinding::bind)

    private val profileViewModel by activityViewModels<ProfileViewModel> { ProfileViewModelFactory() }

    private val viewModel by viewModels<PlaymateCharmStarViewModel>()
    override fun initViews() {
        super.initViews()
        binding.vEvaluate.setListener(object : EvaluateView.OnEvaluateListener {
            override fun onEvaluate(score: Float) {
                binding.btnSubmit.isEnabled = score > 0
            }
        })
        binding.btnSubmit.isEnabled = false
        binding.btnSubmit.onClick {
            submit()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        profileViewModel.userInfoLD.observe(viewLifecycleOwner) {
            updateUI(it)
        }
    }

    private fun updateUI(userInfo: UserInfo?) {
        binding.ivAvatar.setImageUrl(userInfo?.avatar)
    }

    private fun submit() {
        val uid = profileViewModel.userInfoLD?.value?.uid
        if (uid.isNullOrEmpty()) {
            return
        }
        val score = binding.vEvaluate.getScore()
        showLoading()
        viewModel.charmStar(uid, score).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            showToast(rlt)
            when (rlt) {
                is Rlt.Failed -> {
                    //Ntd.
                }

                is Rlt.Success<*> -> {
                    profileViewModel.pullUserInfoBy(uid, true)
                    dismiss()
                }
            }
        }
    }


}