package com.adealink.weparty.room.setting

import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.commonui.widget.CommonDialog
import com.adealink.weparty.room.R
import com.adealink.weparty.room.create.EditRoomDialog
import com.adealink.weparty.room.databinding.DialogRoomSettingBinding
import com.adealink.weparty.room.micseat.dispatcenter.MIC_HOST
import com.adealink.weparty.room.sdk.service.roomService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import com.adealink.weparty.R as APP_R

class RoomSettingDialog : BottomDialogFragment(R.layout.dialog_room_setting) {

    private val binding by viewBinding(DialogRoomSettingBinding::bind)

    override fun initViews() {
        super.initViews()
        binding.btnSetting.show(roomService.joinController.isOwner() || roomService.seatController.getMyMicIndex() == MIC_HOST)
        binding.btnSetting.onClick {
            EditRoomDialog().show(childFragmentManager)
        }

        binding.btnClose.show(roomService.joinController.isOwner())
        binding.btnClose.onClick {
            if (roomService.joinController.isOwner()) {
                closeRoomDialog()
            } else {
                leaveRoom()
            }
        }
    }

    private fun closeRoomDialog() {
        CommonDialog.Builder()
            .title(getCompatString(APP_R.string.common_tips))
            .message(getCompatString(R.string.room_close_tips))
            .positiveText(getCompatString(APP_R.string.common_think_more))
            .negativeText(getCompatString(APP_R.string.commonui_confirm))
            .setShowDefaultCancel(true)
            .onPositive {
                //Ntd.
            }
            .onNegative {
                CoroutineScope(Dispatcher.UI).launch {
                    roomService.joinController.closeRoom()
                }
            }
            .show(childFragmentManager)
    }

    private fun leaveRoom() {
        CoroutineScope(Dispatcher.UI).launch {
            roomService.joinController.leaveRoom(leaveUI = true)
        }
    }

}