package com.ray650128.gstreamer_demo_app.ui.mainScreen

import android.annotation.SuppressLint
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter

class VideoViewAdapter(
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    private var fragments: MutableList<SplitViewFragment> = arrayListOf()

    override fun getItemCount(): Int {
        return fragments.size
    }

    override fun createFragment(position: Int): SplitViewFragment {
        return fragments[position]
    }

    fun add(index: Int, fragment: SplitViewFragment) {
        fragments.add(index, fragment)
        notifyItemChanged(index)
    }

    fun refreshFragment(index: Int, fragment: SplitViewFragment) {
        fragments[index] = fragment
        notifyItemChanged(index)
    }

    fun remove(index: Int) {
        fragments.removeAt(index)
        notifyItemChanged(index)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun clear() {
        fragments.clear()
        notifyDataSetChanged()
    }

    fun pause() {
        for (i in fragments.indices) {
            pause(i)
        }
    }

    fun pause(index: Int) {
        pause(fragments[index])
    }

    private fun pause(fragment: SplitViewFragment) {
        fragment.stopAll()
    }

    fun play(index: Int) {
        play(fragments[index])
    }

    private fun play(fragment: SplitViewFragment) {
        fragment.playAll()
    }

    fun destroy() {
        for (i in fragments.indices) {
            destroy(i)
        }
    }

    fun destroy(index: Int) {
        destroy(fragments[index])
    }

    private fun destroy(fragment: SplitViewFragment) {
        fragment.destroyAll()
    }

    override fun getItemId(position: Int): Long {
        return fragments[position].hashCode().toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        return fragments.find { it.hashCode().toLong() == itemId } != null
    }
}