package com.swago.room.anchor

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.immersionbar.ImmersionBar
import com.swago.baseswago.SwagoAdapter
import com.swago.baseswago.agora.AgoraManager
import com.swago.baseswago.agora.ISwagoIRtcEngineEventHandler
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.RoleType
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.baseroom.ui.AbsAnchorActivity
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.dialog.ChoiceDialogFragment
import com.swago.baseswago.model.live.pk.ProcessPKModel
import com.swago.baseswago.model.live.pk.PunishPKModel
import com.swago.baseswago.model.live.pk.StartPKModel
import com.swago.baseswago.model.live.pk.StopPKModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.DpPxUtil
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.baseswago.util.UserInfo
import com.swago.room.R
import com.swago.room.adapter.GameAdapter
import com.swago.room.base.NoContentFragment
import com.swago.room.bean.UserRoomModel
import com.swago.room.databinding.ActivityAnchorRoomBinding
import com.swago.room.dialog.AnchorCloseDialog
import com.swago.room.dialog.CanStartLiveDialog
import com.swago.room.dialog.ForceCloseRoomDialog
import com.swago.room.lianmai.LianMaiManager
import com.swago.room.lianmai.LianMaiVm
import com.swago.room.pk.IPKListener
import com.swago.room.pk.PKStateManager
import com.swago.room.pk.PkVm
import com.swago.room.service.AgoraForegroundService
import com.swago.room.service.AgoraForegroundService.ACTION_START_FOREGROUND_SERVICE
import com.swago.room.service.AgoraForegroundService.ACTION_STOP_FOREGROUND_SERVICE
import com.swago.room.vm.MsgVm
import com.swago.room.vm.RoomOtherVm
import com.swago.room.vm.RoomVm

/**
 *@date 2021/10/6 10:35
 *description:
 */
@Route(path = ARouteConstant.Room.anchor)
class AnchorRoomActivity : AbsAnchorActivity<ActivityAnchorRoomBinding, IRoomInfo>(),
    ISwagoIRtcEngineEventHandler, IPKListener {

    private val roomVm by viewModels<RoomVm>()
    private val roomOtherVm by viewModels<RoomOtherVm>()
    private val msgVm by viewModels<MsgVm>()
    private val pkVm by viewModels<PkVm>()
    private val lianMaiVm by viewModels<LianMaiVm>()


    private var agoraService: Intent? = null

    private val fragments = arrayListOf(NoContentFragment(), AnchorRoomFragment())

    private val adapter = SwagoAdapter(fragments, supportFragmentManager)

    private var anchorRoomFragment: AnchorRoomFragment? = null

    override fun initLiveData() {
        PKStateManager.resetData()
        roomVm.init()
        msgVm.init()
        pkVm.init()
        lianMaiVm.init()
        PKStateManager.addPKListener(this)
        initPeerAnchorLayoutParams()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        agoraService = Intent(this, AgoraForegroundService::class.java)
        AgoraManager.initializeEngine(this, this)
        AgoraManager.setVideoConfiguration()
        AgoraManager.setClientRole(RoleType.anchor, isNeedVideo = true, isNeedVoice = true)
        AgoraManager.setupLocalVideo(this, binding.flLocal)
        anchorRoomFragment = fragments[1] as AnchorRoomFragment
        binding.viewPager.adapter = adapter

        binding.clPrepare.setOnTouchListener { v, event ->
            return@setOnTouchListener true
        }

        binding.ivPrepareCamera.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                AgoraManager.changeCameraOrientation()
            }
        })
        binding.ivPrepareClose.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                binding.ivPrepareClose.isEnabled = false
                anchorCloseRoom()
            }
        })
        binding.tvStartLive.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                binding.tvStartLive.isEnabled = false
                val userModel = UserRoomModel()
                SwagoRoomManager.changeRoom(userModel)
            }
        })
        binding.ivClose.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                if (LianMaiManager.lianMaiState == 1){
                    ChoiceDialogFragment.newInstance(AppContext.getContext().resources.getString(R.string.lian_mai_ing_sure_close),AppContext.getContext().resources.getString(
                        R.string.tips)).apply {
                        this.sureFun = {
                            lianMaiVm.closeLianMai(){
                                this@AnchorRoomActivity.binding.lianMaiView.closeLianMai(true)
                                SwagoRoomManager.closeRoom()
                            }
                        }
                    }.show(supportFragmentManager,"ChoiceDialogFragment")
                }else{
                    SwagoRoomManager.closeRoom()
                }
            }
        })

        binding.lianMaiView.openCloseLianMaiDialogFun = {
            ChoiceDialogFragment.newInstance(AppContext.getContext().resources.getString(R.string.close_mic_content),AppContext.getContext().resources.getString(
                            R.string.end_lian_mai)).apply {
                this.sureFun = {
                    lianMaiVm.closeLianMai(){
                        this@AnchorRoomActivity.binding.lianMaiView.closeLianMai(true)
                    }
                }
            }.show(supportFragmentManager,"ChoiceDialogFragment")
        }

        msgVm.anchorRoomClosed = {
            SwagoRoomManager.closeRoom()
        }

        msgVm.forceCloseAnchorRoom = {
            ForceCloseRoomDialog.newInstance(it)
                .show(supportFragmentManager, "ForceCloseRoomDialog")
        }

        roomVm.showBannerTime = {
            CanStartLiveDialog.newInstance(it).show(supportFragmentManager, "CanStartLiveDialog")
        }

        roomVm.anchorCloseLiveData.observe(this) {
            val dialog = AnchorCloseDialog.newInstance(it)
            dialog.show(supportFragmentManager, "AnchorCloseDialog")
        }
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
        UserInfo.getUserInfo()?.let {
            AgoraManager.joinChannel(
                iRoomInfo.getChannelName(),
                it.id.toInt(),
                iRoomInfo.getAgoraToken()
            )
        }
        binding.clPrepare.visibility = View.GONE
        binding.viewPager.currentItem = 1
        binding.ivClose.visibility = View.VISIBLE
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {
    }

    override fun receiveStopLive() {

    }

    override fun closeRoomed() {
        PKStateManager.resetData()
        LianMaiManager.clearData()
        AgoraManager.closedRoom()
    }

    override fun onBackPressed() {
        if (binding.clPrepare.visibility == View.VISIBLE) {
            anchorCloseRoom()
        } else {
            SwagoRoomManager.closeRoom()
        }
    }

    private fun anchorCloseRoom() {
        AgoraManager.closePrepareRoom()
        finish()
    }


    override fun onResume() {
        super.onResume()
        agoraService?.let {
            it.action = ACTION_STOP_FOREGROUND_SERVICE
            startService(it)
        }
    }

    override fun onPause() {
        super.onPause()
        agoraService?.let {
            it.action = ACTION_START_FOREGROUND_SERVICE
            startService(it)
        }
    }

    override fun onDestroy() {
        PKStateManager.removePKListener(this)
        agoraService?.let { stopService(it) }
        super.onDestroy()
    }

    override fun onFirstRemoteVideoDecoded(uid: Int, width: Int, height: Int, elapsed: Int) {

    }

    override fun onConnectionStateChanged(state: Int, reason: Int) {


    }

    override fun onChannelMediaRelayStateChanged(state: Int, code: Int) {
        if (PKStateManager.roomState == PKStateManager.PK && state == 2 && code == 0) {
            pkVm.pkSure(PKStateManager.pkId)
        }
    }

    override fun onFirstLocalAudioFramePublished(elapsed: Int) {

    }

    /**************************PK******************************/
    private val marginTopValue by lazy {
        ImmersionBar.getStatusBarHeight(this) + DpPxUtil.dip2px(78f)
    }

    //对方主播id
    private var peerAnchorId = 0
    override fun startPK(startPKModel: StartPKModel, isGetDataFromIM: Boolean) {
        peerAnchorId = startPKModel.oppositeUserId.toInt()
        AgoraManager.startPK(
            startPKModel.roomId,
            startPKModel.oppositeRoomId,
            startPKModel.userId.toInt(),
            startPKModel.sourceToken,
            startPKModel.destToken
        )
        setPKLayoutParams(binding.flLocal, true)
        AgoraManager.setupRemoteVideo(this@AnchorRoomActivity, peerAnchorId, binding.peerFl)

    }

    override fun stopPK(stopPKModel: StopPKModel) {
        AgoraManager.stopPK()
        setPKLayoutParams(binding.flLocal, false)
        AgoraManager.removeRemoteVideo(peerAnchorId, binding.peerFl)
    }

    override fun punishPK(punishPKModel: PunishPKModel, isGetDataFromIM: Boolean) {

    }

    override fun processChangePK(processPKModel: ProcessPKModel, isGetDataFromIM: Boolean) {

    }


    //设置视频画面大小
    private fun setPKLayoutParams(view: View?, isPK: Boolean) {
        if (isPK) {
            val x = DpPxUtil.getScreenWidth() / 2
            val y = DpPxUtil.getScreenWidth() * 275 / 360
            val params = ConstraintLayout.LayoutParams(x, y)
            params.topToTop = R.id.rootAnchorView
            params.startToStart = R.id.rootAnchorView
            params.width = x
            params.height = y
            params.topMargin = marginTopValue
            view?.layoutParams = params
        } else {
            val params = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            view?.layoutParams = params
        }
    }

    private fun initPeerAnchorLayoutParams() {
        val x = DpPxUtil.getScreenWidth() / 2
        val y = DpPxUtil.getScreenWidth() * 275 / 360
        val params = ConstraintLayout.LayoutParams(x, y)
        params.topToTop = R.id.rootAnchorView
        params.endToEnd = R.id.rootAnchorView
        params.width = x
        params.height = y
        params.topMargin = marginTopValue
        binding.peerFl.layoutParams = params
    }

    /************************************************************/

}