using UnityEngine;

public class Joystick : MonoBehaviour
{
    public Canvas m_canvas;
    public RectTransform m_joystick;
    public RectTransform m_background;

    private float m_maxMovement = 0.0f;
    private Vector3 m_initialPosition = Vector3.zero;

    public Vector2 GetNormalizedDirection()
    {
        var localJoystickPosition = m_joystick.transform.localPosition;
        var delta = new Vector2(localJoystickPosition.x, localJoystickPosition.y);
        delta /= m_maxMovement;
        return delta;
    }

    private void Start()
    {
        m_initialPosition = m_joystick.transform.position;
        m_maxMovement = (m_background.rect.width - m_joystick.rect.width) / 2.0f;
    }

    private void Update()
    {
        var newJoystickPosition = Vector3.zero;
        
        if (GetTouchActive())
        {
            var touchPosition = GetTouchPosition();
            var delta = touchPosition - new Vector2(m_initialPosition.x, m_initialPosition.y);
            delta /= m_canvas.scaleFactor;
            
            newJoystickPosition = Vector2.ClampMagnitude(delta, m_maxMovement);
        }
        
        m_joystick.transform.localPosition = newJoystickPosition;
    }

    private static Vector2 GetTouchPosition()
    {
        var result = Vector2.zero;
        
        if (Input.touchCount > 0)
        {
            var touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
            {
                result = touch.position;
            }
        }
        else if (Input.GetMouseButton(0))
        {
            result = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        }
        
        return result;
    }

    private static bool GetTouchActive()
    {
        return Input.touchCount > 0 || Input.GetMouseButton(0);
    }
}