package com.colorful.keyboard.theme.room

import android.content.Context
import androidx.room.Room
import com.colorful.keyboard.theme.bean.DownloadBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class DownloadManager private constructor(context: Context) {

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

    private val downloadDao = database.downloadDao()

    suspend fun insertDownloadBean(downloadBean: DownloadBean) {
        withContext(Dispatchers.IO) {
            val existingDownloadBean = getDownloadBeanByPath(downloadBean.key)
            if (existingDownloadBean == null) {
                downloadDao.insertDownload(downloadBean)
            } else {
                downloadDao.updateDownload(downloadBean)
            }
        }
    }

    suspend fun insertDownloadBeans(downloadBeans: List<DownloadBean>) {
        withContext(Dispatchers.IO) {
            for (downloadBean in downloadBeans) {
                val existingDownloadBean = getDownloadBeanByPath(downloadBean.key)
                if (existingDownloadBean == null) {
                    downloadDao.insertDownload(downloadBean)
                } else {
                    downloadDao.updateDownload(downloadBean)
                }
            }
        }
    }

    suspend fun getAllDownloadBeans(): List<DownloadBean> {
        return withContext(Dispatchers.IO) {
            downloadDao.getAllDownload()
        }
    }

    suspend fun deleteDownloadBean(downloadBean: DownloadBean) {
        withContext(Dispatchers.IO) {
            downloadDao.deleteDownload(downloadBean)
        }
    }

    suspend fun deleteAllDownloadBeans() {
        withContext(Dispatchers.IO) {
            downloadDao.deleteAllDownload()
        }
    }

    suspend fun updateDownloadBeans(downloadBean: DownloadBean) {
        withContext(Dispatchers.IO) {
            downloadDao.updateDownload(downloadBean)
        }
    }

    suspend fun getDownloadBeanByPath(key: String): DownloadBean? {
        return downloadDao.getDownloadByKey(key)
    }


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

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