using UnityEngine;
using UnityEngine.EventSystems;

public class TouchJoystickInput : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    [SerializeField] private RectTransform background;
    [SerializeField] private RectTransform handle;
    [SerializeField] private float handleRange = 50f;

    private Vector2 _input;
    private Canvas _canvas;

    public Vector2 Input => _input;

    private void Start()
    {
        _canvas = GetComponentInParent<Canvas>();
        handle.anchoredPosition = Vector2.zero;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        OnDrag(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            background, eventData.position, eventData.pressEventCamera, out Vector2 localPoint);

        localPoint.x /= background.sizeDelta.x;
        localPoint.y /= background.sizeDelta.y;

        _input = new Vector2(localPoint.x * 2, localPoint.y * 2);
        _input = _input.magnitude > 1f ? _input.normalized : _input;

        handle.anchoredPosition = _input * handleRange;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        _input = Vector2.zero;
        handle.anchoredPosition = Vector2.zero;
    }
}
