package com.zhaohaoting.framework.utils.glid;

import android.content.Context;
import android.support.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.AppGlideModule;
import com.zhaohaoting.framework.utils.DataCache;

/**
 * author：Created by zhaohaoting on 2018/1/10 11:51
 * email：526309416@qq.com
 * desc：注意 一个application只能有一个AppGlideModule实现类
 */
@GlideModule
public class CustomCachingGlideModule extends AppGlideModule {
    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        // 设置磁盘缓存为100M，缓存在内部缓存目录
        int cacheSize100MegaBytes = 1024 * 1024 * 100; // 100 MB;
        builder.setDiskCache(
                new DiskLruCacheFactory(DataCache.getAppDiskCacheRoot(context), cacheSize100MegaBytes)
        );
        // 20%大的内存缓存作为 Glide 的默认值
        MemorySizeCalculator.Builder calculatorBuilder = new MemorySizeCalculator.Builder(context);
        MemorySizeCalculator calculator = calculatorBuilder.build();
        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

        int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
        int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);

        builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
        builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));
    }

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        super.registerComponents(context, glide, registry);
    }
}
