package com.themes.fancy.keyboard.keyboard.myroom

import com.themes.fancy.keyboard.keyboard.data.KbSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object DbManager {

    private val customScope = CoroutineScope(Dispatchers.Main)
    suspend fun addLike(data: KbSource) {
        data.isLike = true
        withContext(Dispatchers.IO) {
            MyDatabase.myDatabase.ThemesDao().insertData(data)
        }

    }

    suspend fun addDownload(data: KbSource) {
        data.isDownload = true
        withContext(Dispatchers.IO) {
            MyDatabase.myDatabase.ThemesDao().insertData(data)
        }

    }

    suspend fun removeLike(data: KbSource) {
        withContext(Dispatchers.IO) {
            val queryIsLike = MyDatabase.myDatabase.ThemesDao().queryIsLike(data.titleName)
            if (queryIsLike != null) {
                if (!queryIsLike.isDownload) {
                    MyDatabase.myDatabase.ThemesDao().delete(queryIsLike)
                } else {
                    queryIsLike.isLike = false
                    MyDatabase.myDatabase.ThemesDao().insertData(queryIsLike)
                }
            }
        }

    }


    suspend fun getIsLike(name: String, action: (isLike: Boolean) -> Unit) {
        withContext(Dispatchers.IO) {
            val query = MyDatabase.myDatabase.ThemesDao().queryIsLike(name)
            withContext(Dispatchers.Main) {
                action.invoke(query != null)
            }
        }

    }
}