package com.swago.baseswago.baseroom.ui

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.OrientationHelper
import com.swago.baseswago.activity.BaseXActivity
import com.swago.baseswago.baseroom.IRoomActiveListener
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.RoleType
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.baseroom.widget.PagerLayoutManager
import com.swago.baseswago.baseroom.widget.RoomAdapter
import com.swago.baseswago.databinding.ActivityAbsRoomUserBinding
import java.util.concurrent.CopyOnWriteArrayList

/**
 *@date 2021/10/10 10:15
 *description:
 */
abstract class AbsUserActivity<T: ActivityAbsRoomUserBinding,E: IRoomInfo> : BaseXActivity<ActivityAbsRoomUserBinding>(), IRoomActiveListener {

    var roleType = RoleType.user

    abstract val roomCoverView:ViewGroup
    abstract var mCurrentPosition:Int
    abstract var iRoomInfos:CopyOnWriteArrayList<E>

    private val adapter:RoomAdapter<E> = RoomAdapter()

    private val pagerLayoutManager  by lazy {
        PagerLayoutManager(this,OrientationHelper.VERTICAL)
    }

    override fun initOther() {
        pagerLayoutManager.setViewGroup(roomCoverView,object:PagerLayoutManager.IreloadInterface{
            override fun onReloadPage(position: Int, isBottom: Boolean, view: View?) {
                var p = position
                if (position == -1000){
                    p = mCurrentPosition
                }
                mCurrentPosition = position
                val mCurrentInfo = iRoomInfos[p]
                SwagoRoomManager.changeRoom(mCurrentInfo)
            }

            override fun onDestroyPage(isNext: Boolean, position: Int, view: View?) {}

        })

        SwagoRoomManager.roleType = roleType
        SwagoRoomManager.addListener(this)
        binding.rv.layoutManager = pagerLayoutManager
        binding.rv.adapter = adapter
        adapter.setNewData(iRoomInfos)
        binding.rv.scrollToPosition(mCurrentPosition)
        pagerLayoutManager.scrollToPositionWithOffset(mCurrentPosition,0)

        initUserRoomView()
    }

    fun scrollToPosition(index:Int){
        binding.rv.scrollToPosition(index)
        pagerLayoutManager.scrollToPositionWithOffset(index,0)
        mCurrentPosition = index
        val mCurrentInfo = iRoomInfos[mCurrentPosition]
        SwagoRoomManager.changeRoom(mCurrentInfo)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (SwagoRoomManager.iRoomInfo!=null){
            SwagoRoomManager.closeRoom()
        }
        SwagoRoomManager.removeListener(this)
        SwagoRoomManager.clearListener()
    }

    abstract fun initUserRoomView()

}