package com.swago.room.anchor

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
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.util.NoDoubleClickListener
import com.swago.baseswago.util.UserInfo
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.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
import com.tencent.qcloud.tim.uikit.TUIKitImpl
import com.tencent.qcloud.tim.uikit.base.IMEventListener
import java.util.*

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

    private val roomVm by viewModels<RoomVm>()
    private val roomOtherVm by viewModels<RoomOtherVm>()
    private val msgVm by viewModels<MsgVm>()


    private var agoraService : Intent? = null

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

    private val adapter = SwagoAdapter(fragments,supportFragmentManager)

    override fun loadData() {}

    private var anchorRoomFragment:AnchorRoomFragment? = null

    override fun initLiveData() {
        roomVm.init()
        msgVm.init()
        roomOtherVm.getGameList()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        agoraService = Intent(this,AgoraForegroundService::class.java)
        AgoraManager.initializeEngine(this,this)
        AgoraManager.setVideoConfiguration()
        AgoraManager.setClientRole(RoleType.anchor)
        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() {
                if (roomVm.currentGameType != -1){
                    binding.tvStartLive.isEnabled = false
                    val userModel = UserRoomModel()
                    SwagoRoomManager.changeRoom(userModel)
                }
            }
        })
        binding.ivClose.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                SwagoRoomManager.closeRoom()
            }
        })

        msgVm.anchorRoomClosed = {
            SwagoRoomManager.closeRoom()
        }

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

        roomOtherVm.gameListModelLiveData.observe(this){
            anchorRoomFragment?.setFooterGameIcon(it.status==1)
            if (it.status == 1){
                binding.rvGame.visibility = View.VISIBLE
            }else {
                binding.rvGame.visibility = View.GONE
            }

            it.list?.let { data ->
                if (data.isNotEmpty()){
                    roomVm.currentGameType = data[0].game_type

                    data[0].selected = true
                    binding.rvGame.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
                    val adapter = GameAdapter()
                    binding.rvGame.adapter = adapter
                    adapter.setNewData(data)
                }
            }
        }
    }

    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 closeRoomed() {
        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() {
        agoraService?.let { stopService(it) }
        super.onDestroy()
    }

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

    }

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


    }

}