package com.atmob.map_amap_android.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.LruCache;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageCacheLoader {

    private static final Handler handler = new Handler(Looper.getMainLooper());

    // 内存缓存
    private static final LruCache<String, Bitmap> memoryCache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8 / 1024)) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getByteCount() / 1024;
        }
    };

    // 同步加载（阻塞，不能在主线程调用）
    public static Bitmap loadBitmap(Context context, String imageUrl) {
        String key = String.valueOf(imageUrl.hashCode());

        // 1. 内存缓存
        Bitmap memoryBitmap = memoryCache.get(key);
        if (memoryBitmap != null) {
            return memoryBitmap;
        }

        // 2. 磁盘缓存
        File cacheDir = new File(context.getCacheDir(), "image_cache");
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
        File imageFile = new File(cacheDir, key + ".png");

        if (imageFile.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            memoryCache.put(key, bitmap);
            return bitmap;
        }

        // 3. 网络下载
        Bitmap bitmap = downloadImage(imageUrl);
        if (bitmap != null) {
            try {
                FileOutputStream fos = new FileOutputStream(imageFile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
                memoryCache.put(key, bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    public static void loadBitmapAsync(final Context context, final String imageUrl, final BitmapCallback callback) {
        // 通知：开始加载
       handler.post(callback::onStartLoading);

        new Thread(() -> {
            try {
                final Bitmap bitmap = loadBitmap(context, imageUrl);
                handler.post(() -> {
                    if (bitmap != null) {
                        callback.onBitmapLoaded(bitmap);
                    } else {
                        callback.onError("图片加载失败，Bitmap 为 null");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                final String message = e.getMessage() != null ? e.getMessage() : "未知错误";
                handler.post(() -> callback.onError("图片加载异常: " + message));
            }
        }).start();
    }


    // 下载图片
    private static Bitmap downloadImage(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect();

            InputStream inputStream = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
