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

import android.content.Context
import androidx.room.Room
import com.offline.music.task.player.db.bean.LocalAudio
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class DatabaseManager private constructor(context: Context) {

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

    private val audioFileDao = database.localAudioDao()

    suspend fun insertAudioFile(localAudio: LocalAudio) {
        withContext(Dispatchers.IO) {
            val existingAudioFile = getAudioFileByPath(localAudio.name)
            if (existingAudioFile == null) {
                audioFileDao.insertAudioFile(localAudio)
            } else {
                audioFileDao.updateAudioFile(localAudio)
            }
        }
    }

    suspend fun insertAudioFiles(localAudios: List<LocalAudio>) {
        withContext(Dispatchers.IO) {
            for (audio in localAudios) {
                val existingAudioFile = getAudioFileByPath(audio.file)
                if (existingAudioFile == null) {
                    audioFileDao.insertAudioFile(audio)
                } else {
                    audioFileDao.updateAudioFile(audio)
                }
            }
        }
    }

    suspend fun getAllAudioFiles(): List<LocalAudio> {
        return withContext(Dispatchers.IO) {
            audioFileDao.getAllAudioFile()
        }
    }

    suspend fun deleteAudioFile(localAudioFile: LocalAudio) {
        withContext(Dispatchers.IO) {
            audioFileDao.deleteAudioFile(localAudioFile)
        }
    }

    suspend fun deleteAllAudioFiles() {
        withContext(Dispatchers.IO) {
            audioFileDao.deleteAllAudioFile()
        }
    }

    suspend fun updateAudioFiles(localAudioFile: LocalAudio) {
        withContext(Dispatchers.IO) {
            audioFileDao.updateAudioFile(localAudioFile)
        }
    }

    suspend fun getAudioFileByPath(path: String): LocalAudio? {
        return audioFileDao.getAudioFileByPath(path)
    }

    suspend fun getAudioBySelect(): List<LocalAudio> {
        return audioFileDao.getAudioBySelected()
    }

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

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