package com.sobot.pictureframe;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.widget.ImageView;

import com.facebook.common.executors.UiThreadImmediateExecutorService;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.sobot.chat.imageloader.SobotImageLoader;

import java.io.File;

public class SobotFrescoImageLoader extends SobotImageLoader {
    @Override
    public void displayImage(Context context, final ImageView imageView, final String path, @DrawableRes int loadingResId, @DrawableRes int failResId, int width, int height, final SobotDisplayImageListener listener) {
        if (TextUtils.isEmpty(path) || "null".equals(path)) {
            return;
        }
        if (imageView == null) {
            return;
        }
        ImageRequestBuilder builder;
        if (path.startsWith("http")) {
            builder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(path));
        } else {
            File file = new File(path);
            if (file != null) {
                builder = ImageRequestBuilder.newBuilderWithSource(Uri.fromFile(file));
            } else {
                builder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(path));
            }
        }
        if (width > 0 && height > 0) {
            builder.setResizeOptions(new ResizeOptions(width, height));
        }
        ImageRequest imageRequest = builder.build();

        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);

        BaseBitmapDataSubscriber subscriber = new BaseBitmapDataSubscriber() {
            @Override
            public void onNewResultImpl(@Nullable Bitmap bitmap) {
                new AsyncTask<Bitmap, Void, Bitmap>() {
                    @Override
                    protected Bitmap doInBackground(Bitmap... params) {
                        Bitmap bitmap = params[0];
                        Bitmap result = null;
                        if (bitmap != null && !bitmap.isRecycled()) {
                            result = bitmap.copy(Bitmap.Config.ARGB_8888, false);
                        }
                        return result;
                    }

                    @Override
                    protected void onPostExecute(Bitmap bitmap) {
                        if (listener != null) {
                            listener.onSuccess(imageView, path);
                        }
                        if (bitmap != null) {
                            imageView.setImageBitmap(bitmap);
                        }
                    }
                }.execute(bitmap);
            }


            @Override
            public void onFailureImpl(DataSource dataSource) {
                if (listener != null) {
                    listener.onFail(imageView, path);
                }
            }
        };

        dataSource.subscribe(subscriber, UiThreadImmediateExecutorService.getInstance());
    }

    @Override
    public void displayImage(Context context, final ImageView imageView, final Uri imgUri, @DrawableRes int loadingResId, @DrawableRes int failResId, int width, int height, final SobotDisplayImageListener listener) {
        if (null == imgUri) {
            return;
        }
        if (imageView == null) {
            return;
        }
        ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(imgUri);
        if (width > 0 && height > 0) {
            builder.setResizeOptions(new ResizeOptions(width, height));
        }
        ImageRequest imageRequest = builder.build();

        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);

        BaseBitmapDataSubscriber subscriber = new BaseBitmapDataSubscriber() {
            @Override
            public void onNewResultImpl(@Nullable Bitmap bitmap) {
                new AsyncTask<Bitmap, Void, Bitmap>() {
                    @Override
                    protected Bitmap doInBackground(Bitmap... params) {
                        Bitmap bitmap = params[0];
                        Bitmap result = null;
                        if (bitmap != null && !bitmap.isRecycled()) {
                            result = bitmap.copy(Bitmap.Config.RGB_565, false);
                        }
                        return result;
                    }

                    @Override
                    protected void onPostExecute(Bitmap bitmap) {
                        if (listener != null) {
                            listener.onSuccess(imageView, imgUri == null ? "" : imgUri.getPath());
                        }
                        if (bitmap != null) {
                            imageView.setImageBitmap(bitmap);
                        }
                    }
                }.execute(bitmap);
            }


            @Override
            public void onFailureImpl(DataSource dataSource) {
                if (listener != null) {
                    listener.onFail(imageView, imgUri == null ? "" : imgUri.getPath());
                }
            }
        };

        dataSource.subscribe(subscriber, UiThreadImmediateExecutorService.getInstance());
    }

    @Override
    public void displayImage(Context context, final ImageView imageView, @DrawableRes int targetResId, @DrawableRes int loadingResId, @DrawableRes int failResId, int width, int height, final SobotDisplayImageListener listener) {
        try {
            if (imageView != null) {
                imageView.setBackgroundResource(targetResId);
            }
        } catch (Exception e) {
        }
    }
}
