package melody.offline.music.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.OptIn
import androidx.fragment.app.Fragment
import androidx.media3.common.util.UnstableApi
import androidx.viewbinding.ViewBinding
import melody.offline.music.sp.AppStore
import melody.offline.music.util.LogTag
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch

@OptIn(UnstableApi::class)
abstract class MoBaseFragment<T : ViewBinding> : Fragment(), CoroutineScope by MainScope() {
    enum class Event {
        FragmentOnResume,
    }

    protected abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> T
    protected lateinit var binding: T
    protected val TAG = LogTag.VO_FRAGMENT_LOG
    protected val appStore by lazy { AppStore(requireContext()) }
    protected val events = Channel<Event>(Channel.UNLIMITED)

    protected abstract suspend fun onViewCreated()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = bindingInflater(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        launch {
            onViewCreated()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        cancel()
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }

    override fun onResume() {
        super.onResume()
        events.trySend(Event.FragmentOnResume)
    }
}
