package com.convenient.android.common.utils.image

import android.graphics.Bitmap
import android.text.TextUtils
import androidx.collection.LruCache

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/8/1
 * description: Bitmap 通过LruCache 进行缓存
 */

class BitmapCaches private constructor() {
    /**
     * 图片缓存的核心对象
     */
    private var mLruCache: LruCache<String, Bitmap>? = null

    /**
     * 从LruCache中获取一张图片，如果不存在就返回null。
     */
    fun getBitmapFromLruCache(key: String): Bitmap? {
        return mLruCache?.get(key)
    }

    @Synchronized
    fun addBitmapToLruCache(key: String, bitmap: Bitmap) {
        if (getBitmapFromLruCache(key) == null) {
            mLruCache?.put(key, bitmap)
        }
    }

    /**
     * 移除缓存
     *
     * @param key
     */
    @Synchronized
    fun removeImageCache(key: String) {
        if (!TextUtils.isEmpty(key)) {
            if (mLruCache != null) {
                val bm = mLruCache?.remove(key)
                bm?.recycle()
            }
        }
    }

    @Synchronized
    fun clearBitmapCache() {
        if (mLruCache != null) {
            if (mLruCache?.size()?:0 > 0) {
                mLruCache?.evictAll()
            }
            mLruCache = null
        }
    }

    companion object {

        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            BitmapCaches()
        }

    }

    init {
        // 获取应用程序最大可用内存
        val maxMemory = Runtime.getRuntime().maxMemory().toInt()
        val cacheSize = maxMemory / 8
        mLruCache = object : LruCache<String, Bitmap>(cacheSize) {
            override fun sizeOf(key: String, value: Bitmap): Int {
                // 重写此方法来衡量每张图片的大小，默认返回图片数量。
                return value.rowBytes * value.height / 1024
            }
        }
    }
}
