package melody.offline.music.database

import android.content.Context
import androidx.room.Room
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import melody.offline.music.bean.Playlist
import melody.offline.music.bean.PlaylistItem

class AppPlaylistDBManager private constructor(context: Context) {

    companion object {
        @Volatile
        private var instance: AppPlaylistDBManager? = null

        fun getInstance(context: Context): AppPlaylistDBManager {
            return instance ?: synchronized(this) {
                instance ?: AppPlaylistDBManager(context).also { instance = it }
            }
        }
    }

    private val database = Room.databaseBuilder(
        context.applicationContext, AppPlaylistDatabase::class.java, "app_playlist_data_base"
    ).build()

    private val playlistDao = database.playlistDao()


    suspend fun insertOrUpdatePlaylist(playlist: Playlist) {
        return withContext(Dispatchers.IO) {
            val existingPlaylist = playlistDao.getPlaylistById(playlist.id)
            if (existingPlaylist == null) {
                playlistDao.insertPlaylist(playlist)
            } else {
                playlistDao.updatePlaylist(playlist)
            }
        }
    }

    suspend fun insertOrUpdatePlaylistItem(playlistItem: PlaylistItem) {
        return withContext(Dispatchers.IO) {
            val existingItem = playlistDao.getPlaylistItemById(playlistItem.id)
            if (existingItem == null) {
                playlistDao.insertPlaylistItem(playlistItem)
            } else {
                playlistDao.updatePlaylistItem(playlistItem)
            }
        }
    }

    suspend fun updatePlaylistItems(playlistItems: List<PlaylistItem>){
        return withContext(Dispatchers.IO){
            playlistDao.updatePlaylistItems(playlistItems)
        }
    }

    suspend fun getPlaylistByTitle(title: String): Playlist? {
        return withContext(Dispatchers.IO) {
            playlistDao.getPlaylistByTitle(title)
        }
    }


    suspend fun getAllPlaylists(): List<Playlist> {
        return withContext(Dispatchers.IO) {
            playlistDao.getAllPlaylists()
        }
    }

    suspend fun getPlaylistItems(playlistId: Int): List<PlaylistItem> {
        return withContext(Dispatchers.IO) {
            playlistDao.getPlaylistItems(playlistId)
        }
    }

    suspend fun deletePlaylist(playlist: Playlist) {
        withContext(Dispatchers.IO) {
            playlistDao.deletePlaylist(playlist)
        }
    }

    suspend fun deletePlaylistItem(playlistItem: PlaylistItem) {
        withContext(Dispatchers.IO) {
            playlistDao.deletePlaylistItem(playlistItem)
        }
    }
}
