package com.ttstd.iconloader;

import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Log;

import androidx.loader.content.AsyncTaskLoader;

public class IconLoader extends AsyncTaskLoader<Drawable> {
    private static final String TAG = "IconLoader";
    private final IconCacheManager mCache;
    private ComponentName mComponentName;

    public IconLoader(Context context, ComponentName componentName, IconCacheManager iconCacheManager) {
        super(context);
        this.mComponentName = componentName;
        this.mCache = iconCacheManager;
    }

    @Override
    protected void onStartLoading() {

    }

    @Override
    public Drawable loadInBackground() {
        String key = CacheKeyGenerator.generateKey(mComponentName);

        // 1. 检查内存缓存
        Drawable cachedIcon = mCache.getFromMemory(key);
        if (cachedIcon != null) {
            return cachedIcon;
        }

        // 2. 检查磁盘缓存
        Drawable diskCached = mCache.getFromDisk(key);
        if (diskCached != null) {
            mCache.putToMemory(key, diskCached);
            Log.e(TAG, "loadInBackground: putToMemory key = " + key);
            return diskCached;
        }

        // 3. 从PackageManager加载组件专属图标
        try {
            PackageManager pm = getContext().getPackageManager();
            ActivityInfo info = pm.getActivityInfo(mComponentName, 0); // 获取ActivityInfo
            Drawable rawIcon = info.loadIcon(pm); // 加载该组件的图标

            // 4. 图标处理（压缩/主题适配）
//            Drawable processedIcon = processIcon(rawIcon);

            // 5. 更新缓存
            mCache.putToMemory(key, rawIcon);
            mCache.putToDisk(key, rawIcon);
            return rawIcon;
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }

    private Drawable processIcon(Drawable icon) {
        // 自适应图标处理（Android 8.0+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                && icon instanceof AdaptiveIconDrawable) {
            AdaptiveIconDrawable adaptiveIcon = (AdaptiveIconDrawable) icon;
            int targetColor = isDarkMode() ? Color.WHITE : Color.BLACK;
            adaptiveIcon.setColorFilter(targetColor, PorterDuff.Mode.SRC_ATOP); // 根据主题切换单色模式
        }

        // 图标尺寸压缩（避免内存溢出）
        if (icon instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
            int scaledWidth = bitmap.getWidth() / 2;
            int scaledHeight = bitmap.getHeight() / 2;
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
            return new BitmapDrawable(getContext().getResources(), scaledBitmap);
        }
        return icon;
    }

    private boolean isDarkMode() {
        return (getContext().getResources().getConfiguration().uiMode
                & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
    }
}