using CoreAnimation;
using Gallery.iOS.Renderers;
using Gallery.Resources.UI;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(BlurryPanel), typeof(BlurryPanelRenderer))]
namespace Gallery.iOS.Renderers
{
    public class BlurryPanelRenderer : ViewRenderer<BlurryPanel, UIVisualEffectView>
    {
        private UIVisualEffectView nativeControl;
        private CALayer bottom;

        protected override void OnElementChanged(ElementChangedEventArgs<BlurryPanel> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                if (bottom != null)
                {
                    if (bottom.SuperLayer != null)
                    {
                        bottom.RemoveFromSuperLayer();
                    }
                    bottom.Dispose();
                    bottom = null;
                }
            }

            if (e.NewElement != null)
            {
                e.NewElement.BackgroundColor = Color.Default;
                if (Control == null)
                {
                    var blur = UIBlurEffect.FromStyle(UIBlurEffectStyle.SystemMaterial);
                    nativeControl = new UIVisualEffectView(blur)
                    {
                        Frame = Frame
                    };
                    SetNativeControl(nativeControl);
                }
            }
        }

        public override void LayoutSubviews()
        {
            base.LayoutSubviews();

            if (nativeControl != null)
            {
                if (bottom == null)
                {
                    bottom = new CALayer
                    {
                        BackgroundColor = UIColor.White.CGColor,
                        ShadowColor = UIColor.Black.CGColor,
                        ShadowOpacity = 1.0f
                    };
                }
                if (bottom.SuperLayer == null)
                {
                    nativeControl.Layer.InsertSublayer(bottom, 0);
                }
                bottom.Frame = new CoreGraphics.CGRect(0, Frame.Height - 5, Frame.Width, 5);
                nativeControl.Frame = Frame;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (bottom != null)
            {
                if (bottom.SuperLayer != null)
                {
                    bottom.RemoveFromSuperLayer();
                }
                bottom.Dispose();
                bottom = null;
            }

            base.Dispose(disposing);
        }
    }
}