package com.adealink.weparty.profile.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.viewmodel.activityViewModels
import com.adealink.frame.router.Router
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.module.im.IM
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.module.profile.data.FollowStatus
import com.adealink.weparty.profile.databinding.LayoutProfileBottomBinding
import com.adealink.weparty.profile.relation.viewmodel.FollowViewModel
import com.adealink.weparty.profile.viewmodel.ProfileViewModelFactory

class ProfileBottomComp(
    lifecycleOwner: LifecycleOwner,
    private val uid: String,
    private val binding: LayoutProfileBottomBinding,
) : BaseProfileViewComp(lifecycleOwner, uid) {

    private val followViewModel by activityViewModels<FollowViewModel> { ProfileViewModelFactory() }

    override fun initView() {
        if (isSelf) {
            binding.clSelf.show()
            binding.clGuest.gone()
        } else {
            binding.clSelf.gone()
            binding.clGuest.show()
        }
        binding.btnFollow.onClick {
            follow()
        }
        binding.btnChat.onClick {
            goChat()
        }
        binding.btnPublishDynamic.onClick {
            publishDynamic()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        if (!isSelf) {
            followViewModel.isFollowLD.observe(viewLifecycleOwner) {
                updateFollow(it[uid] ?: FollowStatus.NONE)
            }
        }
    }

    private fun updateFollow(followStatus: FollowStatus) {
        when (followStatus) {
            FollowStatus.NONE,
            FollowStatus.FANS -> {
                //未关注,对方关注了你
                binding.btnFollow.show()
            }

            FollowStatus.EACH_FOLLOW,
            FollowStatus.FOLLOW -> {
                //互关,已经关注对方
                binding.btnFollow.gone()
            }
        }
    }

    private fun follow() {
        followViewModel.follow(uid).observe(viewLifecycleOwner) {
            showFailedToast(it)
        }
    }

    private fun goChat() {
        val act = activity ?: return
        Router.build(act, IM.Session.PATH)
            .putExtra(IM.Session.EXTRA_CHAT_ID, uid)
            .start()
    }

    private fun publishDynamic() {
        val act = activity ?: return
        Router.build(act, Profile.PublishDynamic.PATH)
            .start()
    }

}