using System;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Pixiview.Droid.Renderers;
using Pixiview.UI;
using Xamarin.Forms;

[assembly: ExportRenderer(typeof(CircleImage), typeof(CircleImageRenderer))]
namespace Pixiview.Droid.Renderers
{
    public class CircleImageRenderer : Xamarin.Forms.Platform.Android.FastRenderers.ImageRenderer
    {
        private Paint paint;
        private int radius;
        private float scale;

        public CircleImageRenderer(Context context) : base(context)
        {
        }

        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            base.OnMeasure(widthMeasureSpec, heightMeasureSpec);

            int size = Math.Min(MeasuredWidth, MeasuredHeight);
            radius = size / 2;
            SetMeasuredDimension(size, size);
        }

        protected override void OnDraw(Canvas canvas)
        {
            paint = new Paint();
            var bitmap = DrawableToBitmap(Drawable);
            if (bitmap == null)
            {
                base.OnDraw(canvas);
                return;
            }
            var bitmapShader = new BitmapShader(bitmap, Shader.TileMode.Clamp, Shader.TileMode.Clamp);
            scale = radius * 2.0f / Math.Min(bitmap.Width, bitmap.Height);

            var matrix = new Matrix();
            matrix.SetScale(scale, scale);
            bitmapShader.SetLocalMatrix(matrix);
            paint.SetShader(bitmapShader);

            canvas.DrawCircle(radius, radius, radius, paint);
        }

        private Bitmap DrawableToBitmap(Drawable drawable)
        {
            if (drawable is BitmapDrawable bd)
            {
                return bd.Bitmap;
            }
            int w = drawable.IntrinsicWidth;
            int h = drawable.IntrinsicHeight;
            var bitmap = Bitmap.CreateBitmap(w, h, Bitmap.Config.Argb8888);
            var canvas = new Canvas(bitmap);
            drawable.SetBounds(0, 0, w, h);
            drawable.Draw(canvas);
            return bitmap;
        }
    }
}
