package com.fastimage;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.LruCache;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.ImageHeaderParserUtils;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CenterInside;
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestOptions;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

// Works out an image's own size for onLoad, as iOS reports it (#608). Glide
// decodes images to fit the view, so the loaded drawable is usually smaller
// than the image.
final class FastImageSourceSize {
    // Sizes of recently decoded images, for loads from the memory cache, which
    // don't decode.
    // (A third value, 1, marks an image drawn as a vector, an SVG: drawn for
    // the box, or at its own size in dp, where a bitmap is decoded at its
    // pixels.)
    private static final LruCache<String, int[]> SIZES = new LruCache<>(500);

    // Whether the image a model loads was drawn as a vector (an SVG), as far
    // as its last decode said.
    static boolean isVector(Object model) {
        int[] size = SIZES.get(String.valueOf(model));
        return size != null && size.length > 2 && size[2] == 1;
    }
    private static final Executor EXECUTOR = Executors.newSingleThreadExecutor();
    private static final Handler MAIN = new Handler(Looper.getMainLooper());

    private FastImageSourceSize() {
    }

    // Wraps the downsample strategy Glide would use, to record the image's
    // size (after EXIF rotation) when Glide decodes it. Views loading the same
    // image at the same size share one decode, which uses the first view's
    // options, so the size is recorded by image rather than by request.
    static final class Capture extends DownsampleStrategy {
        private final DownsampleStrategy strategy;
        // What an SVG is drawn at (see FastImageSvgRenderer): the strategy for
        // the view's scale type, also when images are decoded at full size
        // (downsample false). An SVG has no size of its own to decode at, and
        // drawn at the view's size it's already sharp.
        private final DownsampleStrategy vectorStrategy;
        private final String key;
        // The Capture whose decode on this thread has had its sample size's
        // rounding: Glide's Downsampler asks for the scale factor with the
        // image's size, then for the rounding, then for the scale factor again
        // with the sampled size, which is that call. Per decode, not per
        // Capture: requests made from a clone of another's options (a reload
        // at a new size, a thumbnail) share its Capture, and decode too.
        private static final ThreadLocal<Capture> ROUNDED = new ThreadLocal<>();

        Capture(DownsampleStrategy strategy, String key) {
            this(strategy, strategy, key);
        }

        Capture(DownsampleStrategy strategy, DownsampleStrategy vectorStrategy, String key) {
            this.strategy = strategy;
            this.vectorStrategy = vectorStrategy;
            this.key = key;
        }

        // Whether this is a decode's first call (it has the image's size; see
        // ROUNDED), recording its size.
        private boolean record(int sourceWidth, int sourceHeight, boolean vector) {
            if (ROUNDED.get() == this) {
                ROUNDED.remove();
                return false;
            }
            SIZES.put(key, vector ? new int[]{sourceWidth, sourceHeight, 1} : new int[]{sourceWidth, sourceHeight});
            return true;
        }

        @Override
        public float getScaleFactor(int sourceWidth, int sourceHeight, int requestedWidth, int requestedHeight) {
            boolean first = record(sourceWidth, sourceHeight, false);
            float scale = strategy.getScaleFactor(sourceWidth, sourceHeight, requestedWidth, requestedHeight);
            if (first) recordWork("decode", sourceWidth, sourceHeight, requestedWidth, requestedHeight, scale);
            return scale;
        }

        float getVectorScaleFactor(int sourceWidth, int sourceHeight, int requestedWidth, int requestedHeight) {
            boolean first = record(sourceWidth, sourceHeight, true);
            float scale = vectorStrategy.getScaleFactor(sourceWidth, sourceHeight, requestedWidth, requestedHeight);
            if (first) recordWork("svg", sourceWidth, sourceHeight, requestedWidth, requestedHeight, scale);
            return scale;
        }

        // The image's size, the box it was asked for, and the size it's
        // decoded (or drawn) at, about (before the sample size's rounding).
        private void recordWork(String kind, int sourceWidth, int sourceHeight, int requestedWidth,
                int requestedHeight, float scale) {
            if (!FastImageWork.enabled()) return;
            FastImageWork.record(kind, key, sourceWidth + "x" + sourceHeight
                    + " for " + requestedWidth + "x" + requestedHeight
                    + " at " + Math.round(sourceWidth * scale) + "x" + Math.round(sourceHeight * scale));
        }

        @Override
        public SampleSizeRounding getSampleSizeRounding(int sourceWidth, int sourceHeight, int requestedWidth, int requestedHeight) {
            ROUNDED.set(this);
            return strategy.getSampleSizeRounding(sourceWidth, sourceHeight, requestedWidth, requestedHeight);
        }

        // Glide's memory cache keys include the strategy, so match the wrapped
        // ones to keep sharing cached images between views.
        @Override
        public boolean equals(Object o) {
            return o instanceof Capture && ((Capture) o).strategy.equals(strategy)
                    && ((Capture) o).vectorStrategy.equals(vectorStrategy);
        }

        @Override
        public int hashCode() {
            return 31 * strategy.hashCode() + vectorStrategy.hashCode();
        }
    }

    // What RequestBuilder.into(ImageView) applies for the view's scale type
    // (it leaves a transformation that's already set alone), with the
    // downsample strategy it implies wrapped by capture, and then blur if it
    // isn't null. Not downsampled (downsample false), the image isn't cropped
    // or fitted to the view's size either: the view scales it as it draws it.
    static RequestOptions scaleTypeOptions(
            @Nullable ImageView.ScaleType scaleType,
            Capture capture,
            @Nullable FastImageCrop crop,
            @Nullable FastImageBlur blur,
            boolean downsample) {
        RequestOptions options = new RequestOptions();
        BitmapTransformation transformation = null;
        if (scaleType != null && downsample) {
            switch (scaleType) {
                case CENTER_CROP:
                    if (crop != null) {
                        // At objectPosition, rather than the center.
                        options = options.optionalTransform(crop);
                        transformation = crop;
                        break;
                    }
                    options = options.optionalCenterCrop();
                    transformation = new CenterCrop();
                    break;
                case CENTER_INSIDE:
                case FIT_XY:
                    options = options.optionalCenterInside();
                    transformation = new CenterInside();
                    break;
                case FIT_CENTER:
                case FIT_START:
                case FIT_END:
                    options = options.optionalFitCenter();
                    transformation = new FitCenter();
                    break;
                default:
                    break;
            }
        }
        if (blur != null) {
            options = transformation == null
                    ? options.optionalTransform(blur)
                    : options.optionalTransform(new MultiTransformation<>(transformation, blur));
        }
        return options.downsample(capture);
    }

    static Capture capture(@Nullable ImageView.ScaleType scaleType, Object model, boolean downsample) {
        DownsampleStrategy strategy = strategy(scaleType);
        return new Capture(downsample ? strategy : FULL_SIZE, strategy, String.valueOf(model));
    }

    private static DownsampleStrategy strategy(@Nullable ImageView.ScaleType scaleType) {
        if (scaleType == null) return DownsampleStrategy.DEFAULT;
        switch (scaleType) {
            case CENTER:
                return FULL_SIZE;
            case CENTER_CROP:
                return DownsampleStrategy.CENTER_OUTSIDE;
            case CENTER_INSIDE:
            case FIT_XY:
                return DownsampleStrategy.CENTER_INSIDE;
            case FIT_CENTER:
            case FIT_START:
            case FIT_END:
                return DownsampleStrategy.FIT_CENTER;
            default:
                return DownsampleStrategy.DEFAULT;
        }
    }

    // At the image's own size (objectFit none shows it at that size, whatever
    // the view's, and downsample false decodes every image this way), or
    // scaled down to at most MAX_PIXELS pixels, which a bitmap can be drawn at
    // (Android won't draw one over 100 MB).
    static final DownsampleStrategy FULL_SIZE = new FullSize();

    static final float MAX_PIXELS = 4096f * 4096f;

    // The scale that brings this many pixels down to at most MAX_PIXELS, or 1.
    static float capScale(float pixels) {
        return pixels > MAX_PIXELS ? (float) Math.sqrt(MAX_PIXELS / pixels) : 1;
    }

    // The box (in pixels) Glide decodes an image for in a view: the view's
    // size, or that scaled down to at most MAX_PIXELS pixels, keeping its
    // shape. Glide crops or fits an image to the box, scaling it up if it's
    // smaller, so a very large view (e.g. a long image shown full width) would
    // get a bitmap its size, which Android won't draw over 100 MB ("Canvas:
    // trying to draw too large bitmap"). The view scales it up as it draws it.
    static int[] box(int width, int height) {
        float scale = capScale((float) width * height);
        if (width <= 0 || height <= 0 || scale == 1) return new int[]{width, height};
        return new int[]{
                Math.max(1, (int) Math.floor(width * scale)),
                Math.max(1, (int) Math.floor(height * scale))};
    }

    private static final class FullSize extends DownsampleStrategy {
        @Override
        public float getScaleFactor(int sourceWidth, int sourceHeight, int requestedWidth, int requestedHeight) {
            return capScale((float) sourceWidth * sourceHeight);
        }

        @Override
        public SampleSizeRounding getSampleSizeRounding(int sourceWidth, int sourceHeight, int requestedWidth, int requestedHeight) {
            return SampleSizeRounding.QUALITY;
        }
    }

    // The image's size, or null when it has to be read from a local image's
    // header first (see readLocal).
    @Nullable
    static int[] get(Drawable resource, Object model, boolean local, boolean fromResourceCache) {
        String key = String.valueOf(model);
        if (resource instanceof GifDrawable) {
            // Glide decodes GIFs itself (sampled to fit the view), without the
            // downsample strategy; their header has the size.
            int[] size = gifSize((GifDrawable) resource);
            if (size != null) return size;
        } else if (fromResourceCache) {
            // Glide caches local images already resized for the view, and the
            // decode from there recorded the resized size.
            SIZES.remove(key);
            return null;
        } else {
            int[] size = SIZES.get(key);
            if (size != null) return size;
            if (local) return null;
        }
        return new int[]{resource.getIntrinsicWidth(), resource.getIntrinsicHeight()};
    }

    @Nullable
    private static int[] gifSize(GifDrawable gif) {
        ByteBuffer buffer = gif.getBuffer();
        if (buffer == null || buffer.limit() < 10) return null;
        // The logical screen width and height (little-endian) follow the
        // 6-byte signature.
        int width = (buffer.get(6) & 0xff) | (buffer.get(7) & 0xff) << 8;
        int height = (buffer.get(8) & 0xff) | (buffer.get(9) & 0xff) << 8;
        return new int[]{width, height};
    }

    interface Callback {
        // read: whether it's the image's own size, read from it (or else the
        // decoded image's).
        void onSize(int[] size, boolean read);
    }

    // Whether get gives a loaded image's own size (a GIF's from its header, or
    // the size its decode recorded or a read found), rather than the decoded
    // image's.
    static boolean knows(Drawable resource, Object model) {
        if (resource instanceof GifDrawable) return gifSize((GifDrawable) resource) != null;
        return SIZES.get(String.valueOf(model)) != null;
    }

    // An image loaded from Glide's resource disk cache, already resized for a
    // view: the size its decode recorded is that size, not its own (see get).
    static void forgetResized(Object model) {
        SIZES.remove(String.valueOf(model));
    }

    // Reads a local image's size from its header, off the main thread.
    static void readLocal(Context context, final FastImageSource source, final Drawable resource, final Object model, final Callback callback) {
        final Context appContext = context.getApplicationContext();
        EXECUTOR.execute(new Runnable() {
            @Override
            public void run() {
                int[] size = readBounds(appContext, source);
                final boolean read = size != null;
                if (read) {
                    SIZES.put(String.valueOf(model), size);
                } else {
                    size = new int[]{resource.getIntrinsicWidth(), resource.getIntrinsicHeight()};
                }
                final int[] result = size;
                MAIN.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onSize(result, read);
                    }
                });
            }
        });
    }

    @Nullable
    private static int[] readBounds(Context context, FastImageSource source) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            InputStream stream = open(context, source);
            try {
                BitmapFactory.decodeStream(stream, null, options);
            } finally {
                stream.close();
            }
            if (options.outWidth <= 0 || options.outHeight <= 0) return null;
            int orientation;
            stream = open(context, source);
            try {
                Glide glide = FastImageGlide.get(context);
                orientation = ImageHeaderParserUtils.getOrientation(
                        glide.getRegistry().getImageHeaderParsers(), stream, glide.getArrayPool());
            } finally {
                stream.close();
            }
            // EXIF orientations 5 to 8 rotate by 90 or 270 degrees.
            boolean rotated = orientation >= 5 && orientation <= 8;
            return rotated
                    ? new int[]{options.outHeight, options.outWidth}
                    : new int[]{options.outWidth, options.outHeight};
        } catch (IOException | RuntimeException e) {
            return null;
        }
    }

    private static InputStream open(Context context, FastImageSource source) throws IOException {
        if (source.isBase64Resource()) {
            String data = source.getDataUri();
            byte[] bytes = Base64.decode(data.substring(data.indexOf(',') + 1), Base64.DEFAULT);
            return new ByteArrayInputStream(bytes);
        }
        Uri uri = source.getUri();
        String path = uri.getPath();
        if ("file".equals(uri.getScheme()) && path != null && path.startsWith("/android_asset/")) {
            return context.getAssets().open(path.substring("/android_asset/".length()));
        }
        InputStream stream = context.getContentResolver().openInputStream(uri);
        if (stream == null) throw new IOException("Can't open " + uri);
        return stream;
    }
}
