package six.ca.crashcases.fragment.data

import android.app.ActivityManager
import android.content.Context
import android.util.LruCache
import kotlin.math.roundToInt


/**
 * @author hellenxu
 * @date 2021-01-18
 * Copyright 2021 Six. All rights reserved.
 */
object MemoryDataSource {

    private var cachePercentage = 0.1
//    private var m = 1024 * 1024f
    private val lruCache: LruCache<String, String>

    init {
        val runtime = Runtime.getRuntime()
//        val maxMemory = runtime.maxMemory() / m
//        val freeMemory = runtime.freeMemory() / m
//        val totalMemory = runtime.totalMemory() / m

//        val actManager = appCtx.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
//        println("xxl-memory11: per-app-memory-normal= ${actManager.memoryClass}; per-app-memory-large= ${actManager.largeMemoryClass}")
//
//        val memoryInfo = ActivityManager.MemoryInfo()
//        actManager.getMemoryInfo(memoryInfo)
//        println("xxl-memory22: total= ${memoryInfo.totalMem / m}; available= ${memoryInfo.availMem / m}")

        val availableMemory = runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory()
        val cacheSize = availableMemory * cachePercentage
        println("xxl-cache-size: $cacheSize")

        lruCache = object: LruCache<String, String>(cacheSize.roundToInt()) {
            override fun sizeOf(key: String?, value: String): Int {
                val tmp = value.toByteArray().size
                println("xxl-byte-array-size: $tmp")

                return tmp
            }
        }

    }

    fun putCache(key: String, value: String) {
        println("xxl-cache-put: $key; $value")
        if (key.isBlank() || value.isBlank()) {
            return
        }

        lruCache.put(key, value)
    }


    fun getCache(key: String): String? {
        println("xxl-cache-get: $key")

        return lruCache.get(key)
    }

}