package com.unibuy.smartdevice.ui.tools;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.signature.ObjectKey;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsFileNullException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsMalformedURLException;
import com.unibuy.smartdevice.tools.HttpConnect;
import com.unibuy.smartdevice.tools.Tools;
import android.util.Log;

import java.io.File;
import java.security.MessageDigest;

public class ImageGlide {
    private final Context context;

    public ImageGlide(Context context) {
        this.context = context;
    }

    public void fileload(String urlString, ImageView imageView) throws LogsEmptyException {
        if (imageView == null)
            return;

        Context ctx = imageView.getContext();
        if (ctx instanceof Activity) {
            Activity activity = (Activity) ctx;
            if (activity.isFinishing() || activity.isDestroyed()) {
                // 安全檢查：Activity 已被銷毀，避免 Glide crash
                return;
            }
        }

        HttpConnect httpConnect = new HttpConnect();
        try {
            File imageFile = httpConnect.getFileFromUrl(urlString);
            if (imageFile.exists()) {
                Glide.with(imageView).load(imageFile)
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.loading)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .signature(new ObjectKey(System.currentTimeMillis())) // 強制更新
                        .into(imageView);
            } else {
                Glide.with(imageView).load(urlString)
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.loading)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .signature(new ObjectKey(System.currentTimeMillis())) // 強制更新
                        .into(imageView);
            }
        } catch (LogsFileNullException e) {
            Glide.with(imageView).load(urlString)
                    .placeholder(R.drawable.loading)
                    .error(R.drawable.loading)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .signature(new ObjectKey(System.currentTimeMillis())) // 強制更新
                    .into(imageView);
        }
    }

    public void preload(String urlString) throws LogsEmptyException {
        preload(urlString, false);
    }

    public void preload(String urlString, boolean force) throws LogsEmptyException {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            if (activity.isFinishing() || activity.isDestroyed()) {
                return; // 防止 preload 在被銷毀 Activity 執行
            }
        }

        HttpConnect httpConnect = new HttpConnect();
        try {
            File imageFile = httpConnect.download(urlString, force);
            Glide.with(context.getApplicationContext()).load(imageFile)
                    .placeholder(R.drawable.loading)
                    .error(R.drawable.loading)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .signature(new ObjectKey(imageFile.lastModified()))
                    .preload();
        } catch (LogsFileNullException | LogsMalformedURLException | LogsIOException e) {
            Glide.with(context.getApplicationContext()).load(urlString)
                    .placeholder(R.drawable.loading)
                    .error(R.drawable.loading)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .preload();
        }
    }

    public static class WhiteTintTransformation extends BitmapTransformation {
        private final String ID = "com.unibuy.smartdevice.ui.tools.ImageGlide.WhiteTintTransformation";
        private final byte[] ID_BYTES = ID.getBytes(CHARSET);

        private final int alpha; // 白色濾鏡的不透明度 (0 - 255)

        public WhiteTintTransformation(int alpha) {
            this.alpha = alpha;
        }

        @Override
        protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
            // 將圖像疊加白色濾鏡
            return applyWhiteTint(toTransform, alpha);
        }

        private Bitmap applyWhiteTint(Bitmap source, int alpha) {
            Bitmap result = source.copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(result);

            // 設置白色濾鏡
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColorFilter(new PorterDuffColorFilter(0xFFFFFFFF, PorterDuff.Mode.SRC_ATOP));
            paint.setAlpha(alpha); // 設定白色濾鏡的不透明度

            // 在圖像上疊加白色
            canvas.drawBitmap(result, 0, 0, paint);

            return result;
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof WhiteTintTransformation) {
                WhiteTintTransformation other = (WhiteTintTransformation) o;
                return alpha == other.alpha;
            }
            return false;
        }

        @Override
        public int hashCode() {
            return ID.hashCode() + alpha;
        }

        @Override
        public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
            messageDigest.update(ID_BYTES);
            messageDigest.update((byte) alpha);
        }
    }

    /**
     * 清理商品圖片暫存 (Tools.getExternalFilesDir())
     */
    public static void clearProductCache(Context context) {
        File dir = Tools.getExternalFilesDir();
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    String name = file.getName().toLowerCase();
                    if (name.endsWith(".png") || name.endsWith(".jpg") || name.endsWith(".jpeg")
                            || name.endsWith(".webp")) {
                        if (file.delete()) {
                            Log.i("ImageGlide", "Deleted product cache: " + name);
                        }
                    }
                }
            }
        }
    }
}
