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

import android.content.Context
import androidx.room.Room
import com.offline.music.task.player.db.bean.CurrentPlayingLocalAudio
import com.offline.music.task.player.db.bean.CurrentPlayingLocalAudioDao

class CurrentAudioManager private constructor(context: Context) {
    private val database: CurrentAudioDatabase = Room.databaseBuilder(
        context.applicationContext,
        CurrentAudioDatabase::class.java, "current_audio_app_database"
    ).build()

    private val currentPlayingLocalAudioDao: CurrentPlayingLocalAudioDao = database.currentPlayingAudioDao()

    suspend fun getCurrentPlayingAudio(): CurrentPlayingLocalAudio? {
        return currentPlayingLocalAudioDao.getCurrentPlayingAudio()
    }

    suspend fun setCurrentPlayingAudio(audio: CurrentPlayingLocalAudio) {
        val currentAudio = getCurrentPlayingAudio()
        if (currentAudio == null) {
            currentPlayingLocalAudioDao.insertCurrentPlayingAudio(audio)
        } else {
            // 如果已有数据，先删除现有数据，然后再插入新数据
            currentPlayingLocalAudioDao.deleteCurrentPlayingAudio(currentAudio)
            currentPlayingLocalAudioDao.insertCurrentPlayingAudio(audio)
        }
    }

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

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