package com.offline.music.task.player.tools.media

import android.content.ComponentName
import android.content.Context
import android.net.Uri
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.Player
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 com.offline.music.task.player.ProApp
import com.offline.music.task.player.R

import com.offline.music.task.player.db.bean.Audio
import com.offline.music.task.player.db.bean.CurrentPlayingAudio
import com.offline.music.task.player.service.LocalPlaybackService
import com.offline.music.task.player.tools.util.containsContent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


//LOGO
object MediaControllerManager {
    private var mediaController: MediaController? = null
    private var controllerFuture: ListenableFuture<MediaController>? = null
    private var currentAudioFile = ""

    fun init(context: Context) {
        val sessionToken =
            SessionToken(context, ComponentName(context, LocalPlaybackService::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 setupMedia(context: Context, audio: Audio, listener: Player.Listener) {
        if (currentAudioFile != audio.file) {
            currentAudioFile = audio.file

            val uri: Uri? = if (containsContent(audio.file)) {
                Uri.parse(audio.file)
            } else {
                Uri.parse("file:///android_asset/$currentAudioFile")
            }
            val resourceId = R.mipmap.ic_launcher
            val imgUri: Uri? = if (audio.image.isNotEmpty()) {
                Uri.parse("file:///android_asset/${audio.image}")
            } else {
                Uri.parse("android.resource://${context.packageName}/$resourceId")
            }

            val mediaItem =
                MediaItem.Builder()
                    .setUri(uri)
                    .setMediaMetadata(
                        MediaMetadata.Builder()
                            .setArtist(audio.name)
                            .setTitle(audio.name)
                            .setArtworkUri(imgUri)
                            .build()
                    )
                    .build()
            if (isConnected()) {
                mediaController?.let {
                    it.addListener(listener)
                    it.setMediaItem(mediaItem)
                    it.repeatMode = Player.REPEAT_MODE_ONE
                    it.prepare()
                    it.play()
                    val currentPlayingAudio =
                        CurrentPlayingAudio(
                            audio.id,
                            audio.name,
                            audio.file,
                            audio.image,
                            audio.duration,
                            false
                        )
                    CoroutineScope(Dispatchers.IO).launch {
                        ProApp.currentAudioManager.setCurrentPlayingAudio(currentPlayingAudio)
                        withContext(Dispatchers.Main) {
                            ProApp.initCurrentPlayingAudio()//更新到入口变量中
                        }
                    }
                }
            }
        }
    }

    fun setupMedia(context: Context, audio: CurrentPlayingAudio, listener: Player.Listener) {
        if (currentAudioFile != audio.file) {
            currentAudioFile = audio.file

            val uri: Uri? = if (containsContent(audio.file)) {
                Uri.parse(audio.file)
            } else {
                Uri.parse("file:///android_asset/$currentAudioFile")
            }
            val resourceId = R.mipmap.ic_launcher
            val imgUri: Uri? = if (audio.image.isNotEmpty()) {
                Uri.parse("file:///android_asset/${audio.image}")
            } else {
                Uri.parse("android.resource://${context.packageName}/$resourceId")
            }

//            val uri = Uri.parse("file:///android_asset/$currentAudioFile")
////            val mediaItem = MediaItem.fromUri(uri)
//            val imgUri = Uri.parse("file:///android_asset/${audio.image}")
            val mediaItem =
                MediaItem.Builder()
                    .setUri(uri)
                    .setMediaMetadata(
                        MediaMetadata.Builder()
                            .setArtist(audio.name)
                            .setTitle(audio.name)
                            .setArtworkUri(imgUri)
                            .build()
                    )
                    .build()
            if (isConnected()) {
                mediaController?.let {
                    it.addListener(listener)
                    it.setMediaItem(mediaItem)
                    it.repeatMode = Player.REPEAT_MODE_ONE
                    it.prepare()
                    it.play()
                    val currentPlayingAudio =
                        CurrentPlayingAudio(
                            audio.id,
                            audio.name,
                            audio.file,
                            audio.image,
                            audio.duration,
                            false
                        )
                    CoroutineScope(Dispatchers.IO).launch {
                        ProApp.currentAudioManager.setCurrentPlayingAudio(currentPlayingAudio)
                        withContext(Dispatchers.Main) {
                            ProApp.initCurrentPlayingAudio()//更新到入口变量中
                        }
                    }

                }
            }
        }
    }

    fun isConnected(): Boolean {
        mediaController?.let {
            return it.isConnected
        }
        return false
    }


    fun isPlaying(): Boolean {
        mediaController?.let {
            return it.isPlaying
        }
        return false
    }
}
