package com.swago.room.user

import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.viewModels
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.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.dialog.ReportDialog
import com.swago.baseswago.model.MomentModel
import com.swago.baseswago.util.AppContext
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.databinding.LayoutUserRoomBinding
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 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>() {

    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 bindingCoverView:LayoutUserRoomBinding? = null

    private var userRoomFragment:UserRoomFragment? = null

    override val roomCoverView: ViewGroup by lazy {
        bindingCoverView = LayoutUserRoomBinding.inflate(layoutInflater)
        bindingCoverView!!.viewPager.adapter = adapter
        bindingCoverView!!.viewPager.currentItem = 1
        bindingCoverView!!.root
    }


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

    override fun initOther() {
        AgoraManager.initializeEngine(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)

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

            ivReport.setOnClickListener(object:NoDoubleClickListener(){
                override fun onClick() {
                    SwagoRoomManager.iRoomInfo?.let {
                        ReportDialog.newInstance(it.getAnchorCode())
                            .show(supportFragmentManager, "ReportDialog")
                    }
                }
            })
        }
    }

    override fun loadData() {
    }

    override fun initLiveData() {
        msgVm.anchorRoomClosed = {
            userRoomFragment?.dismissDialog()
            bindingCoverView?.userShowAnchorCloseView?.visibility = View.VISIBLE
            it?.let { bindingCoverView?.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){
            bindingCoverView?.userShowAnchorCloseView?.visibility = View.VISIBLE
            it?.let { bindingCoverView?.userShowAnchorCloseView?.setData(it)  }
        }
    }

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

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

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

    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()
    }
}