using CoreAnimation;
using Pixiview.iOS.Renderers;
using Pixiview.UI;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(RoundImage), typeof(RoundImageRenderer))]
namespace Pixiview.iOS.Renderers
{
    public class RoundImageRenderer : ImageRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);

            var layer = Layer;
            if (layer != null && e.NewElement is RoundImage image)
            {
                bool flag = false;
                if (image.CornerRadius > 0)
                {
                    layer.CornerRadius = image.CornerRadius;
                    flag = true;
                }
                var mask = image.CornerMasks;
                if (mask != CornerMask.None)
                {
                    var m = default(CACornerMask);
                    if ((mask & CornerMask.LeftTop) == CornerMask.LeftTop)
                    {
                        m |= CACornerMask.MinXMinYCorner;
                    }
                    if ((mask & CornerMask.RightTop) == CornerMask.RightTop)
                    {
                        m |= CACornerMask.MaxXMinYCorner;
                    }
                    if ((mask & CornerMask.LeftBottom) == CornerMask.LeftBottom)
                    {
                        m |= CACornerMask.MinXMaxYCorner;
                    }
                    if ((mask & CornerMask.RightBottom) == CornerMask.RightBottom)
                    {
                        m |= CACornerMask.MaxXMaxYCorner;
                    }

                    layer.MaskedCorners = m;
                    flag = true;
                }
                if (flag)
                {
                    layer.MasksToBounds = true;
                }
            }
        }
    }
}
