package com.adealink.weparty.room.applymic

import android.Manifest
import androidx.fragment.app.viewModels
import com.adealink.frame.aab.util.getCompatString
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.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.room.data.MIC_ASSIGN_BY_REMOTE
import com.adealink.weparty.permission.PermissionUtils
import com.adealink.weparty.room.R
import com.adealink.weparty.room.applymic.viewmodel.ApplyMicViewModel
import com.adealink.weparty.room.databinding.DialogRoomApplyMicBinding
import com.adealink.weparty.room.viewmodel.RoomViewModelFactory

class ApplyMicDialog : BottomDialogFragment(R.layout.dialog_room_apply_mic) {

    private val binding by viewBinding(DialogRoomApplyMicBinding::bind)

    private val viewModel by viewModels<ApplyMicViewModel> { RoomViewModelFactory() }

    private var applyMicIndex = MIC_ASSIGN_BY_REMOTE

    fun setApplyMic(index: Int) {
        applyMicIndex = index
    }


    override fun initViews() {
        super.initViews()
        val userInfo = ProfileModule.getMyUserInfo()
        binding.ivAvatar.setImageUrl(userInfo?.avatar)
        binding.tvName.text = userInfo?.nickName
        binding.btnApply.onClick {
            applyMic()
        }
    }

    private fun applyMic() {
        requestRecordAudioPermission({ granted ->
            if (granted) {
                applyMicInner()
            }
        })

    }

    private fun applyMicInner() {
        showLoading()
        viewModel.applyMic(applyMicIndex).observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    showToast(rlt)
                    dismiss()
                }
            }
        }
    }

    private fun requestRecordAudioPermission(callback: ((granted: Boolean) -> Unit)) {
        PermissionUtils.requestPermissionWithRetry(
            requireActivity(),
            Manifest.permission.RECORD_AUDIO,
            getCompatString(R.string.room_record_audio_permission_tip),
            0,
        ) { granted, recordAudioTipLimited ->
            callback.invoke(granted)
        }
    }

}