using System.Threading.Tasks;
using Pixiview.iOS.Effects;
using Pixiview.Utils;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ResolutionGroupName("Pixiview")]
[assembly: ExportEffect(typeof(LongPressEffectImplement), "LongPressEffect")]
namespace Pixiview.iOS.Effects
{
    public class LongPressEffectImplement : PlatformEffect
    {
        private bool attached;
        private readonly UILongPressGestureRecognizer longPressGesture;

        public LongPressEffectImplement()
        {
            longPressGesture = new UILongPressGestureRecognizer(OnLongPressed);
        }

        protected override void OnAttached()
        {
            if (!attached)
            {
                attached = true;
                Container.AddGestureRecognizer(longPressGesture);
            }
        }

        protected override void OnDetached()
        {
            if (attached)
            {
                attached = false;
                Container.RemoveGestureRecognizer(longPressGesture);
            }
        }

        private void OnLongPressed(UILongPressGestureRecognizer e)
        {
            if (e.State != UIGestureRecognizerState.Began)
            {
                return;
            }
            var element = Element;
            if (element != null)
            {
                var command = LongPressEffect.GetCommand(element);
                if (command != null)
                {
                    var o = LongPressEffect.GetCommandParameter(element);
                    command.Execute(o);
                }
            }
        }
    }
}
