package com.lemenzo.gallery.editor;

import android.graphics.Bitmap;
import android.graphics.RectF;

/** Crop helpers. Normalized crop bounds use the 0..1 range and are clamped safely. */
public final class CropController {
    private CropController() {}

    public static Bitmap crop(Bitmap source, RectF normalizedBounds) {
        if (source == null) throw new IllegalArgumentException("source == null");
        if (normalizedBounds == null) return source;
        float left = clamp(normalizedBounds.left);
        float top = clamp(normalizedBounds.top);
        float right = clamp(normalizedBounds.right);
        float bottom = clamp(normalizedBounds.bottom);
        if (right <= left || bottom <= top) throw new IllegalArgumentException("Invalid crop bounds");
        int x = Math.min(source.getWidth() - 1, Math.max(0, Math.round(left * source.getWidth())));
        int y = Math.min(source.getHeight() - 1, Math.max(0, Math.round(top * source.getHeight())));
        int r = Math.min(source.getWidth(), Math.max(x + 1, Math.round(right * source.getWidth())));
        int b = Math.min(source.getHeight(), Math.max(y + 1, Math.round(bottom * source.getHeight())));
        return Bitmap.createBitmap(source, x, y, r - x, b - y);
    }

    public static Bitmap centerCrop(Bitmap source, float aspectRatio) {
        if (source == null) throw new IllegalArgumentException("source == null");
        if (aspectRatio <= 0f) throw new IllegalArgumentException("aspectRatio <= 0");
        int width = source.getWidth();
        int height = source.getHeight();
        float current = width / (float) height;
        if (Math.abs(current - aspectRatio) < 0.0001f) return source;
        if (current > aspectRatio) {
            int targetWidth = Math.max(1, Math.round(height * aspectRatio));
            int left = (width - targetWidth) / 2;
            return Bitmap.createBitmap(source, left, 0, targetWidth, height);
        }
        int targetHeight = Math.max(1, Math.round(width / aspectRatio));
        int top = (height - targetHeight) / 2;
        return Bitmap.createBitmap(source, 0, top, width, targetHeight);
    }

    private static float clamp(float value) {
        return Math.max(0f, Math.min(1f, value));
    }
}
