package com.lemenzo.gallery.editor;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;

import java.util.List;

/** Flattens visible markup/redaction/text into an exported copy. */
public final class EditOverlayRenderer {
    private EditOverlayRenderer() {}
    public static void renderInPlace(Bitmap bitmap, List<EditorAnnotation> annotations) {
        if (bitmap == null || annotations == null || annotations.isEmpty()) return;
        Canvas canvas = new Canvas(bitmap);
        float w = bitmap.getWidth(), h = bitmap.getHeight();
        Paint stroke = new Paint(Paint.ANTI_ALIAS_FLAG); stroke.setColor(Color.WHITE); stroke.setStyle(Paint.Style.STROKE); stroke.setStrokeCap(Paint.Cap.ROUND); stroke.setStrokeJoin(Paint.Join.ROUND); stroke.setStrokeWidth(Math.max(3f,w*.006f));
        Paint redact = new Paint(Paint.ANTI_ALIAS_FLAG); redact.setColor(Color.BLACK); redact.setStyle(Paint.Style.FILL);
        Paint text = new Paint(Paint.ANTI_ALIAS_FLAG); text.setColor(Color.WHITE); text.setTextSize(Math.max(24f,w*.055f)); text.setShadowLayer(Math.max(2f,w*.003f),0f,1f,Color.BLACK); canvas.setDrawFilter(new android.graphics.PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
        for (EditorAnnotation a : annotations) {
            if (a == null || a.points == null) continue;
            if (a.type == EditorAnnotation.TYPE_STROKE && a.points.size() >= 4) {
                Path p = new Path(); p.moveTo(a.points.get(0)*w,a.points.get(1)*h);
                for(int i=2;i+1<a.points.size();i+=2)p.lineTo(a.points.get(i)*w,a.points.get(i+1)*h);
                canvas.drawPath(p,stroke);
            } else if(a.type==EditorAnnotation.TYPE_REDACTION&&a.points.size()>=4){float x1=a.points.get(0)*w,y1=a.points.get(1)*h,x2=a.points.get(2)*w,y2=a.points.get(3)*h;canvas.drawRect(Math.min(x1,x2),Math.min(y1,y2),Math.max(x1,x2),Math.max(y1,y2),redact);
            } else if(a.type==EditorAnnotation.TYPE_TEXT&&a.points.size()>=2&&a.text!=null){float x=a.points.get(0)*w,y=a.points.get(1)*h;float tw=text.measureText(a.text);canvas.drawText(a.text,x-tw/2f,y,text);}
        }
    }
}
