package com.keyboard.craft.db

import android.content.Context
import androidx.room.Room
import com.keyboard.craft.bean.ItemDataBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class DatabaseManager private constructor(context: Context) {

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

    private val audioFileDao = database.localLikeDao()

    suspend fun insertItemDataBeanFile(audio: ItemDataBean) {
        withContext(Dispatchers.IO) {
            val existingItemDataBeanFile = getItemDataBeanFileByPath(audio.key)
            if (existingItemDataBeanFile == null) {
                audioFileDao.insertItemDataBeanFile(audio)
            } else {
                audioFileDao.updateItemDataBeanFile(audio)
            }
        }
    }

    suspend fun insertItemDataBeanFiles(audios: List<ItemDataBean>) {
        withContext(Dispatchers.IO) {
            for (audio in audios) {
                val existingItemDataBeanFile = getItemDataBeanFileByPath(audio.key)
                if (existingItemDataBeanFile == null) {
                    audioFileDao.insertItemDataBeanFile(audio)
                } else {
                    audioFileDao.updateItemDataBeanFile(audio)
                }
            }
        }
    }

    suspend fun getAllItemDataBeanFiles(): List<ItemDataBean> {
        return withContext(Dispatchers.IO) {
            audioFileDao.getAllItemDataBeanFile()
        }
    }

    suspend fun deleteItemDataBeanFile(audioFile: ItemDataBean) {
        withContext(Dispatchers.IO) {
            audioFileDao.deleteItemDataBeanFile(audioFile)
        }
    }

    suspend fun deleteAllItemDataBeanFiles() {
        withContext(Dispatchers.IO) {
            audioFileDao.deleteAllItemDataBeanFile()
        }
    }

    suspend fun updateItemDataBeanFiles(audioFile: ItemDataBean) {
        withContext(Dispatchers.IO) {
            audioFileDao.updateItemDataBeanFile(audioFile)
        }
    }

    suspend fun getItemDataBeanFileByPath(path: String): ItemDataBean? {
        return audioFileDao.getItemDataBeanFileByPath(path)
    }

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

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