using Godot;
using System;

namespace lettergodot
{
    public class DragAndDrop : KinematicBody2D
    {
        private static ulong dragging = ulong.MaxValue;

        private bool Dragging
        {
            get => GetInstanceId() == dragging;
            set => dragging = value ? GetInstanceId() : ulong.MaxValue;
        }
        

        public override void _Ready()
        {
            Connect("dragsignal", this, "DragSignalImplemenmtation");
        }

        public override void _Process(float delta)
        {
            if (Dragging)
            {
                var mousepos = GetViewport().GetMousePosition();
                Position = new Vector2(mousepos.x, mousepos.y);
            }
        }

        [Signal]
        public delegate void dragsignal();

        private void DragSignalImplemenmtation()
        {
            Dragging = !Dragging;
        }


        public override void _Input(InputEvent @event)
        {
            
            if (@event is InputEventMouseButton)
            {
                var eventMouseButton = (InputEventMouseButton)@event;
                
                
                if (eventMouseButton.ButtonIndex == (int)ButtonList.Left && eventMouseButton.Pressed)
                {
                    
                    
                  // log Position and Position
                  GD.Print("Position: " + Position);
                  GD.Print("MousePosition:" + eventMouseButton.Position);
                  GD.Print("Length:" + (eventMouseButton.Position - Position).Length());
                    if ((eventMouseButton.Position - Position).Length() < (60) )
                    {
                        EmitSignal("dragsignal");
                    }
                }
                else if (eventMouseButton.ButtonIndex == (int)ButtonList.Left && !eventMouseButton.Pressed)
                {
                    if ((eventMouseButton.Position - Position).Length() < (60))
                    {
                        EmitSignal("dragsignal");
                    }
                }
            }
            else if (@event is InputEventScreenTouch)
            {
                var eventScreenTouch = (InputEventScreenTouch)@event;

                if ((eventScreenTouch.Position - Position).Length() < (60))
                {
                    if (eventScreenTouch.Pressed && eventScreenTouch.Index == 0)
                    {
                        Position = eventScreenTouch.Position;
                    }
                }
            }
        }
    }
}