package com.adealink.weparty.room

import android.content.Intent
import android.view.KeyEvent
import androidx.activity.viewModels
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.room.data.LeaveRoomReason
import com.adealink.frame.room.data.RoomState
import com.adealink.frame.room.data.TAG_ROOM
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.share.shareManager
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.module.room.Room
import com.adealink.weparty.room.chatroom.ChatRoomFragment
import com.adealink.weparty.room.constant.logRoomTime
import com.adealink.weparty.room.databinding.ActivityRoomBinding
import com.adealink.weparty.room.interceptor.EnterRoomUriInterceptor
import com.adealink.weparty.room.listener.IRoomOpListener
import com.adealink.weparty.room.minimize.manager.minimizeRoomManager
import com.adealink.weparty.room.sdk.service.roomService
import com.adealink.weparty.room.viewmodel.RoomFlowViewModel
import com.adealink.weparty.room.viewmodel.RoomViewModelFactory
import java.util.LinkedList

@RouterUri(
    path = [Room.Room.PATH],
    interceptors = [EnterRoomUriInterceptor::class],
    desc = "语音房间"
)
class RoomActivity : BaseActivity(), IRoomOpListener {

    companion object {
        private const val TAG = "RoomActivity"

        private const val CHAT_FRAGMENT = "room_fragment"

        private const val REJOIN_TIP_DIALOG = "RejoinTipDialog"
    }

    private val binding by viewBinding(ActivityRoomBinding::inflate)

    override val forceFitNavigationBar: Boolean
        get() = true

    //默认聊天房间
    private var roomFragment: BaseRoomFragment? = null


    private val flowViewModel by viewModels<RoomFlowViewModel> { RoomViewModelFactory() }


    // 权限申请队列, RxPermissions 申请权限时, 必须等前面那个完成才能申请下一个, 不然连续调用后面的会无效
    private val requestPermissionPending = LinkedList<(onFinished: () -> Unit) -> Unit>()
    private var requestingPermission = false

    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Router.bind(this)
    }

    override fun initViews() {
        logRoomTime("RoomActivity initViews")
        setContentView(binding.root)
        setNavigationBarColor(com.adealink.weparty.R.color.black)
        switchToChatRoom()
    }

    override fun handleNewIntent(intent: Intent?) {
        super.handleNewIntent(intent)
        roomFragment?.handleNewIntent(intent)
    }

    override fun onStart() {
        super.onStart()
        //检查当前房间信息是否丢失
        val roomId = roomService.joinController.getJoinedRoomId()
        if (roomId.isNullOrEmpty()) {
            Log.i(TAG_ROOM, "RoomActivity onStart, roomId is 0, finish()")
            //当前房间已经销毁,finish
            finish()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        flowViewModel.roomStateLD.observe(this) {
            when (it.state) {
                RoomState.ROOM_IN -> {
                    //当"ROOM_IN"时,此时已经房间的信息已经完整
//                    inflateRoomFragment(roomService.attrController.getRoomType())
//                    (supportFragmentManager.findFragmentByTag(REJOIN_TIP_DIALOG) as? CommonDialog)?.dismiss()
                }

                RoomState.ROOM_LEAVE -> {
                    val flowStateInfo = it.flow
                    if (flowStateInfo.leaveUI) {
                        finish()
                    }
                }

                else -> {}
            }
        }
    }

    private fun switchToChatRoom() {
        if (roomFragment is ChatRoomFragment) {
            return
        }

        ChatRoomFragment.newInstance().let {
            roomFragment = it
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.fl_room, it, CHAT_FRAGMENT)
                .commitAllowingStateLoss()
        }
    }


    internal fun addRequestPermissionPending(block: (onFinished: () -> Unit) -> Unit) {
        requestPermissionPending.add(block)
        requestNextPermission()
    }

    private fun requestNextPermission() {
        if (requestingPermission) {
            return
        }
        val poll = requestPermissionPending.poll() ?: return
        Log.d(TAG, "requestNextPermission: ")
        requestingPermission = true
        poll.invoke {
            requestingPermission = false
            requestNextPermission()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return super.onKeyDown(keyCode, event)
//        if(isFinishing || isDestroyed) return true
//        return if (event?.keyCode == KeyEvent.KEYCODE_BACK) {
//            showRoomCloseTipDialog()
//            true
//        } else {
//            super.onKeyDown(keyCode, event)
//        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        shareManager.onActivityResult(requestCode, resultCode, data)
    }

    override fun showRoomCloseTipDialog(reason: LeaveRoomReason) {
//        RoomCloseTipDialog.newInstance(
//            object : ICloseRoomActionListener {
//                override fun onRoomMinimizeClick() {
//                    roomFragment?.onRoomMinimize {
//                        if (it) {
//                            doRoomMinimize()
//                        }
//                    } ?: doRoomMinimize()
//                }
//
//                private fun doRoomMinimize() {
//                    RoomBaseStatEvent.reportBtnClick(
//                        RoomBaseStatEvent.Btn.CLOSE_ROOM,
//                        RoomBaseStatEvent.Result.OPEN
//                    )
//                    finish()
//                }
//
//                override fun onRoomCloseClick() {
//                    if (roomService.seatController.showCancelOnMicApplyDialog(null) {
//                            handleExitRoom(LeaveRoomReason.INITIATIVE)
//                        }) {
//                        return
//                    }
//                    roomFragment?.onRoomClose {
//                        if (it) {
//                            exitRoom(reason)
//                        }
//                    } ?: exitRoom(reason)
//                }
//            }
//        ).show(supportFragmentManager)
    }

    override fun exitRoom(reason: LeaveRoomReason) {
        handleExitRoom(reason)
    }

    private fun handleExitRoom(reason: LeaveRoomReason) {
        minimizeRoomManager.removeMinimizedRoomView()
        flowViewModel.tryLeaveRoom(reason)
        finish()
    }

}
