package com.gh.gamecenter.setting.compose.viewmodel

import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import com.gh.gamecenter.core.runOnIoThread
import java.io.File

class ComposeSettingViewModel(application: Application) : AndroidViewModel(application) {
    var cacheSizeState by mutableStateOf("")

    // 获取缓存大小
    fun getCacheSize() {
        runOnIoThread {
            val ecDir = getApplication<Application>().externalCacheDir
            var cacheLength: Long = getFolderSize(getApplication<Application>().cacheDir)
            if (ecDir != null) {
                cacheLength += getFolderSize(ecDir)
            }
            cacheSizeState = long2Size(cacheLength)
        }
    }

    private fun long2Size(length: Long): String {
        val m = length / 1024f / 1024f
        var str = m.toString()
        val index = str.lastIndexOf(".")
        if (index != -1 && str.length > index + 3) {
            str = str.substring(0, index + 3)
        }
        return str + "M"
    }

    private fun getFolderSize(folder: File): Long {
        var size: Long = 0
        //忽略视频缓存
        if (folder.name == "video-cache" || folder.name == "exo") return size
        size += folder.length()
        if (folder.isDirectory) {
            val files = folder.listFiles()
            if (files == null || files.isEmpty()) return size
            for (file in files) {
                size += if (file.isDirectory) {
                    getFolderSize(file)
                } else {
                    file.length()
                }
            }
        }
        return size
    }

}