package melody.offline.music.media

import android.content.ComponentName
import android.content.Context
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import melody.offline.music.service.PlaybackService

object MediaControllerManager {
    private var mediaController: MediaController? = null
    private var controllerFuture: ListenableFuture<MediaController>? = null

    fun init(context: Context) {
        val sessionToken =
            SessionToken(context, ComponentName(context, PlaybackService::class.java))
        controllerFuture = MediaController.Builder(context, sessionToken).buildAsync()
        controllerFuture?.addListener({
            mediaController = controllerFuture?.get()
        }, MoreExecutors.directExecutor())
    }

    fun getController(): MediaController? {
        return if (mediaController != null && mediaController!!.isConnected) {
            mediaController
        } else {
            null
        }
    }

    fun getDuration(): Long {
        mediaController?.let {
            if (it.duration > 0) {
                return it.duration
            } else {
                return 0
            }
        }
        return 0
    }

    fun getCurrentPosition(): Long {
        mediaController?.let {
            if (it.currentPosition > 0 && it.currentPosition < it.duration) {
                return it.currentPosition
            } else {
                return 0
            }
        }
        return 0
    }

    fun getBufferedPosition(): Long {
        mediaController?.let {
            if (it.bufferedPosition > 0) {
                return it.bufferedPosition
            } else {
                return 0
            }
        }
        return 0
    }
}
