package xn.hxp.ui.login.ext;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageDecoder;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import com.king.logx.LogX;

import java.io.IOException;

public class BitmapExt {

    public interface DrawRectBlock {
        void drawBlock(Canvas canvas, Paint paint);
    }

    public static Bitmap drawRect(Bitmap source, DrawRectBlock block) {
        if (source == null) return null;

        // 创建新的 Bitmap 对象 [9,10](@ref)
        Bitmap result = Bitmap.createBitmap(
                source.getWidth(),
                source.getHeight(),
                Bitmap.Config.ARGB_8888
        );

        try {
            Canvas canvas = new Canvas(result);
            canvas.drawBitmap(source, 0f, 0f, null);

            Paint paint = new Paint();
            paint.setStrokeWidth(6f);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.RED);

            block.drawBlock(canvas, paint);
            canvas.save();
            canvas.restore();
        } catch (Exception e) {
            LogX.w(e);
        }
        return result;
    }

    public static Bitmap getBitmap(Context context, Uri uri) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                ImageDecoder.Source source = ImageDecoder.createSource(
                        context.getContentResolver(),
                        uri
                );
                return ImageDecoder.decodeBitmap(source).copy(
                        Bitmap.Config.ARGB_8888,
                        true
                );
            } else {
                return MediaStore.Images.Media.getBitmap(
                        context.getContentResolver(),
                        uri
                );
            }
        } catch (IOException e) {
            LogX.w(e);
            return null;
        }
    }
}