package com.adealink.weparty.storage.config

import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.stat.IStat
import com.adealink.frame.storage.config.IStorageConfig
import com.adealink.frame.storage.file.IFileStorageConfig
import com.adealink.frame.util.ONE_MINUTE
import com.adealink.frame.util.deleteFiles
import com.adealink.frame.util.runOnUiThread
import com.adealink.weparty.App
import com.adealink.weparty.storage.file.FilePath
import com.adealink.weparty.storage.stat.StorageStatEvent
import java.io.File

class StorageConfig : IStorageConfig, IStat {

    init {
        runOnUiThread({
            clearOldStorage()
        }, 5 * ONE_MINUTE)
    }

    override val spRootDir: String?
        get() = FilePath.spPath
    override val stat: IStat = this
    override val deviceId: String
        get() = App.instance.deviceIdService.getMemDeviceId() //这里只能使用mem device id，不要从sp中加载，避免mmkv错误引入的循环调用堆栈溢出

    override val fileStorageConfig: IFileStorageConfig = object : IFileStorageConfig {

        override val cacheMaxSize: Long = 500 * 1024 * 1024

    }

    override fun stat(events: Map<String, String>) {
        StorageStatEvent()
            .apply {
                addEventMap(events)
            }
            .send()
    }

    private fun clearOldStorage() {
        Dispatcher.wenextThreadPoolExecutor.submit {
            val dirList = arrayListOf(
                FilePath.oldGiftPath,
                FilePath.oldEmotionPath,
                FilePath.oldMusicPath,
                FilePath.oldThemePath,
                FilePath.oldSkinPath,
                FilePath.oldCarPath,
                FilePath.oldActivityPath,
                FilePath.oldRocketPath,
                FilePath.oldLevelPath,
                FilePath.oldCpPath,
                FilePath.oldVideoPath,
                FilePath.oldEffectPath,
                FilePath.oldBackupEffectPath,
                FilePath.oldLabelPath,
                FilePath.oldWeddingPath,
                FilePath.oldFamilyPath,
                )
            for (dir in dirList) {
                dir.let {
                    try {
                        deleteFiles(File(it))
                    } catch (_: Exception) {

                    }
                }
            }
        }
    }

}