using Android.Content;
using Billing.Droid.Renderers;
using Billing.UI;
using System;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(LongPressGrid), typeof(LongPressGridRenderer))]
namespace Billing.Droid.Renderers
{
    public class LongPressGridRenderer : ViewRenderer<LongPressGrid, Android.Views.View>
    {
        public LongPressGridRenderer(Context context) : base(context)
        {
        }

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

            if (e.OldElement != null)
            {
                if (Control != null)
                {
                    Control.LongClick -= Grid_LongClick;
                }
            }

            if (e.NewElement != null)
            {
                if (Control == null)
                {
                    var view = new Android.Views.View(Context)
                    {
                        Clickable = true,
                        LongClickable = true
                    };
                    view.Click += Grid_Click;
                    view.LongClick += Grid_LongClick;
                    SetNativeControl(view);
                }
            }
        }

        private void Grid_Click(object sender, EventArgs e)
        {
            var gesture = Element?.GestureRecognizers?.FirstOrDefault(g => g is TapGestureRecognizer);
            if (gesture is TapGestureRecognizer tap)
            {
                if (tap.Command != null && tap.Command.CanExecute(tap.CommandParameter))
                {
                    tap.Command.Execute(tap.CommandParameter);
                }
            }
        }

        private void Grid_LongClick(object sender, LongClickEventArgs e)
        {
            Element.TriggerLongPress();
        }
    }
}