package com.swago.room.user

import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.swago.baseswago.SwagoAdapter
import com.swago.baseswago.UserVm
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.AbsUserActivity
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.databinding.ActivityAbsRoomUserBinding
import com.swago.baseswago.model.MomentModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.LogUtil
import com.swago.baseswago.util.NoDoubleClickListener
import com.swago.baseswago.util.UserInfo
import com.swago.room.R
import com.swago.room.base.NoContentFragment
import com.swago.room.bean.UserRoomModel
import com.swago.room.data.RoomDataManager
import com.swago.room.service.AgoraForegroundService
import com.swago.room.vm.MsgVm
import com.swago.room.vm.RoomOtherVm
import com.swago.room.vm.RoomVm
import com.swago.room.widget.UserShowAnchorCloseView
import jp.wasabeef.glide.transformations.BlurTransformation
import java.util.concurrent.CopyOnWriteArrayList

/**
 *@date 2021/10/11 14:12
 *description:
 */
@Route(path = ARouteConstant.Room.user)
class UserRoomActivity : AbsUserActivity<ActivityAbsRoomUserBinding, UserRoomModel>(),
    ISwagoIRtcEngineEventHandler {

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

    private var agoraService: Intent? = null

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

    private val adapter = SwagoAdapter(fragments, supportFragmentManager)

    @Autowired
    @JvmField
    var position: Int = 0

    @Autowired
    @JvmField
    var data: ArrayList<MomentModel>? = null

    private var userRoomFragment: UserRoomFragment? = null

    private var ivClose: ImageView? = null
    private var ivCover: ImageView? = null
    private var userShowAnchorCloseView: UserShowAnchorCloseView? = null
    private var flRoot: FrameLayout? = null

    override val roomCoverView: ViewGroup by lazy {
        val userRoomView = layoutInflater.inflate(R.layout.layout_user_room, null) as ViewGroup
        val viewPager = userRoomView.findViewById<ViewPager>(R.id.viewPager)
        ivClose = userRoomView.findViewById(R.id.ivClose)
        userShowAnchorCloseView = userRoomView.findViewById(R.id.userShowAnchorCloseView)
        ivCover = userRoomView.findViewById(R.id.ivCover)
        flRoot = userRoomView.findViewById(R.id.flRoot)
        viewPager.adapter = adapter
        viewPager.currentItem = 1
        userRoomView
    }


    override var mCurrentPosition: Int = position
    override var iRoomInfos: CopyOnWriteArrayList<UserRoomModel> = RoomDataManager.data

    override fun initOther() {
        AgoraManager.initializeEngine(this, this)
        ARouter.getInstance().inject(this)
        mCurrentPosition = position
        RoomDataManager.initData(data)
        super.initOther()
        userRoomFragment = fragments[1] as UserRoomFragment
    }

    override fun initUserRoomView() {
        roomVm.init()
        msgVm.init()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        agoraService = Intent(this, AgoraForegroundService::class.java)

        AgoraManager.setVideoConfiguration()
        AgoraManager.setClientRole(RoleType.user)

        ivClose?.setOnClickListener(object : NoDoubleClickListener() {
            override fun onClick() {
                SwagoRoomManager.closeRoom()
            }
        })
    }

    override fun loadData() {
    }

    override fun initLiveData() {
        msgVm.anchorRoomClosed = {
            userShowAnchorCloseView?.visibility = View.VISIBLE
            it?.let { userShowAnchorCloseView?.setData(it) }
        }

        msgVm.kickFromRoom = {
            Toast.makeText(
                AppContext.getContext(),
                AppContext.getContext().resources.getString(R.string.be_kick_out),
                Toast.LENGTH_SHORT
            ).show()
            SwagoRoomManager.closeRoom()
        }

        roomVm.roomClosedLiveData.observe(this) {
            userShowAnchorCloseView?.visibility = View.VISIBLE
            it?.let { userShowAnchorCloseView?.setData(it) }
        }
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
        isRobot = iRoomInfo.getIsRobot()
        ivCover?.let {
            Glide.with(this)
                .load(iRoomInfo.getRoomCover())
                .dontAnimate()
                .apply(RequestOptions.bitmapTransform(BlurTransformation(5, 100)))
                .into(it)
        }
        ivCover?.visibility = View.VISIBLE
        userShowAnchorCloseView?.visibility = View.INVISIBLE
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
        AgoraManager.changeRoom(iRoomInfo.getAnchorId().toInt(), flRoot)
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
        if (iRoomInfo.getIsRobot()) {
            ivCover?.visibility = View.GONE
        }
        UserInfo.getUserInfo()?.let { userInfoModel ->
            AgoraManager.joinChannel(
                iRoomInfo.getChannelName(),
                userInfoModel.id.toInt(),
                iRoomInfo.getAgoraToken()
            )
            if (!isRobot) {
                flRoot?.let {
                    AgoraManager.setupRemoteVideo(
                        this@UserRoomActivity,
                        iRoomInfo.getAnchorId().toInt(), it
                    )
                }
            }
        }
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {
    }

    override fun closeRoomed() {
        AgoraManager.closedRoom()
    }

    override fun onBackPressed() {
        SwagoRoomManager.closeRoom()
    }

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

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

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

    private var isRobot = false
    override fun onFirstRemoteVideoDecoded(uid: Int, width: Int, height: Int, elapsed: Int) {
        if (!isRobot) {
            ivCover?.visibility = View.GONE
        }
    }

    override fun onConnectionStateChanged(state: Int, reason: Int) {
        LogUtil.d("网络变更", "$state----$reason")
    }
}