package com.swago.room.audio

import android.graphics.Rect
import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.swago.baseswago.cusview.SwagoRecyclerView
import com.swago.baseswago.dialog.BaseListDialogFragment
import com.swago.baseswago.model.live.audio.AudioInviteUserModel
import com.swago.baseswago.util.DpPxUtil
import com.swago.room.databinding.DialogAudioCanInviteBinding
import com.swago.room.vm.RoomVm

class AudioCanInviteDialog : BaseListDialogFragment<DialogAudioCanInviteBinding, AudioInviteUserModel>() {

    private val roomVm by activityViewModels<RoomVm>()

    init {
        setGravity(Gravity.BOTTOM)
        setCanCancel(true)
        setDimAmount(0f)
    }

    override val smartRecyclerView: SwagoRecyclerView<AudioInviteUserModel> by lazy {
        binding.swagoRv as SwagoRecyclerView<AudioInviteUserModel>
    }
    override val adapter: BaseQuickAdapter<AudioInviteUserModel, *> by lazy {
        AudioInviteAdapter()
    }
    override val layoutManager: RecyclerView.LayoutManager by lazy {
        LinearLayoutManager(context)
    }
    override val loadData: (page: Int) -> Unit = {
        roomVm.getCanAudioInviteUserList()
    }

    companion object{
        fun newInstance(maiIndex:Int): AudioCanInviteDialog {
            val args = Bundle()
            args.putInt("maiIndex",maiIndex)
            val fragment = AudioCanInviteDialog()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initViewData() {
        arguments?.let {
            val maiIndex = it.getInt("maiIndex",0)
            smartRecyclerView.recyclerView?.addItemDecoration(ListItemDecoration())
            adapter.setOnItemChildClickListener { _, _, position ->
                if (adapter.data.size>position){
                    roomVm.inviteUserOnMic(adapter.data[position].user_id,maiIndex)
                    dismissAllowingStateLoss()
                }
            }
        }
    }

    override fun initLiveData() {
        roomVm.audioInvitedUserListLiveData.observe(this){
            if (it == null){
                smartRecyclerView.onFetchDataError()
            }else{
                smartRecyclerView.onFetchDataFinish(it,true)
            }
        }
    }

    override fun loadMoreNeed(): Boolean {
        return false
    }


    inner class ListItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val margin = DpPxUtil.dip2px(8f)
            outRect.set(0, 0, 0, margin)
        }
    }

}