package org.libre.agosto.p2play.singletons

import android.content.ComponentName
import android.content.Context
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import com.google.common.util.concurrent.MoreExecutors
import org.libre.agosto.p2play.models.VideoModel
import org.libre.agosto.p2play.services.PlaybackService

object PlaybackSingleton {
    var player: ExoPlayer? = null
    var video: VideoModel? = null
    private var withMediaSession = false

    fun setData(mediaItem: MediaItem, video: VideoModel): ExoPlayer? {
        player?.let {
            if (it.isPlaying) {
                it.pause()
            }
            it.setMediaItem(mediaItem)
            it.prepare()
            this.video = video
            return it
        }

        return null
    }

    fun release() {
        player?.release()
    }

    fun runMediaSession(context: Context) {
        if (!this.withMediaSession) {
            val sessionToken = SessionToken(context, ComponentName(context, PlaybackService::class.java))

            val controllerFuture = MediaController.Builder(context, sessionToken).buildAsync()

            controllerFuture.addListener(
                {
                    val med = controllerFuture.get()
                },
                MoreExecutors.directExecutor(),
            )
            this.withMediaSession = true
        }
    }
}
