using Billing.iOS.Renderers;
using Billing.UI;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(LongPressGrid), typeof(LongPressGridRenderer))]
namespace Billing.iOS.Renderers
{
    public class LongPressGridRenderer : ViewRenderer<LongPressGrid, UIView>
    {
        private UILongPressGestureRecognizer longGesture;

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

            if (e.OldElement != null && longGesture != null)
            {
                RemoveGestureRecognizer(longGesture);
                longGesture = null;
            }

            if (e.NewElement != null)
            {
                longGesture = new UILongPressGestureRecognizer(OnLongPressed);
                AddGestureRecognizer(longGesture);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (longGesture != null)
            {
                RemoveGestureRecognizer(longGesture);
                longGesture = null;
            }

            base.Dispose(disposing);
        }

        private void OnLongPressed(UILongPressGestureRecognizer e)
        {
            if (e.State == UIGestureRecognizerState.Began && Element != null)
            {
                Element.TriggerLongPress();
            }
        }
    }
}