package com.adealink.weparty.webview

import com.adealink.frame.base.fastLazy
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.data.json.froJsonErrorNull
import com.adealink.frame.data.json.toJsonErrorNull
import com.adealink.frame.util.AppUtil
import com.adealink.frame.util.createDirByDeleteOldDir
import com.adealink.frame.util.getDirSizeBytes
import com.adealink.frame.util.runOnUiThread
import com.adealink.weparty.storage.file.FilePath
import com.adealink.weparty.webview.datasource.local.WebLocalService
import kotlinx.coroutines.withContext
import java.io.File

object WebModule {

    private val offlineH5UrlSet by fastLazy {
        froJsonErrorNull<MutableSet<String>>(WebLocalService.offlineH5UrlsJson) ?: mutableSetOf()
    }

    fun clearCache() {
        runOnUiThread {
            AppUtil.currentActivity?.let {
                WeNextWebView(it).clearCache(true)
            }
        }
        Dispatcher.wenextThreadPoolExecutor.execute {
            createDirByDeleteOldDir(FilePath.webPath)
        }
    }

    suspend fun getCacheSize(): Long {
        return withContext(Dispatcher.WENEXT_THREAD_POOL) {
            return@withContext FilePath.webPath?.let {
                getDirSizeBytes(File(it))
            } ?: 0L
        }
    }

    fun addOfflineH5Url(url: String) {
        offlineH5UrlSet.add(url)
        WebLocalService.offlineH5UrlsJson = toJsonErrorNull(offlineH5UrlSet) ?: ""
    }

    fun getOfflineH5Urls(): Set<String> {
        return offlineH5UrlSet
    }

}