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.FavoriteBean

class AppFavoriteDBManager private constructor(context: Context) {

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

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

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

    private val dao = database.localFavoriteDao()

    suspend fun insertFavoriteBean(bean: FavoriteBean) {
        withContext(Dispatchers.IO) {
            val offlineBean = getFavoriteBeanByID(bean.videoId)
            if (offlineBean == null) {
                dao.insertFavoriteBean(bean)
            } else {
                dao.updateFavoriteBean(bean)
            }
        }
    }

    suspend fun insertOfflineListBean(list: List<FavoriteBean>) {
        withContext(Dispatchers.IO) {
            for (bean in list) {
                val offlineBean = getFavoriteBeanByID(bean.videoId)
                if (offlineBean == null) {
                    dao.insertFavoriteBean(bean)
                } else {
                    dao.updateFavoriteBean(bean)
                }
            }
        }
    }

    suspend fun getAllFavoriteBeans(): List<FavoriteBean> {
        return withContext(Dispatchers.IO) {
            dao.getAllFavoriteBeans()
        }
    }

    suspend fun deleteFavoriteBean(bean: FavoriteBean) {
        withContext(Dispatchers.IO) {
            dao.deleteFavoriteBean(bean)
        }
    }

    suspend fun deleteAllFavoriteBean() {
        withContext(Dispatchers.IO) {
            dao.deleteAllFavoriteBean()
        }
    }

    suspend fun updateFavoriteBean(bean: FavoriteBean) {
        withContext(Dispatchers.IO) {
            dao.updateFavoriteBean(bean)
        }
    }

    suspend fun getFavoriteBeanByID(id: String): FavoriteBean? {
        return dao.getFavoriteBeanByID(id)
    }
}
