
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TMPro;

/// <summary>
/// This class can be used to transform any game object
/// </summary>
public class DVScaleIcon : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IMoveHandler
{

    /// <summary>
    /// The object which will be scaled when the icon is activated
    /// </summary>
    [SerializeField] Transform objectToScale;
    private PointerEventData pointerEvent;
    private Vector2? previousPosition;

    void LateUpdate()
    {
        if (pointerEvent != null)
        {
            Vector2 position = pointerEvent.position;
            try
            {
                Vector2 delta = position - (previousPosition ?? position);
                if (delta.x != 0 && delta.y != 0)
                {
                    float aspectRatio = objectToScale.localScale.y / objectToScale.localScale.x;
                    float change = (delta.x - delta.y) / 500;
                
                    if (change < -0.1) change = -0.1f;
                    if (change > 0.1) change = 0.1f;

                    var newTransformX = objectToScale.transform.localScale.x + change;
                    var newTransformY = (objectToScale.transform.localScale.x + change) * aspectRatio;

                    if (newTransformX > 0.25)
                        objectToScale.localScale = new Vector3(newTransformX, newTransformY, 1);
                }
            }
            catch (Exception e)
            {
                Debug.Log("ERROR UPDATING SCALE");
            }
            previousPosition = position;
        }
    }

    /// <summary>
    /// When the pointer is down, set the scale event origin to be used in calculating scale deltas
    /// </summary>
    /// <param name="data">The pointer event data</param>
    public void OnPointerDown(PointerEventData data)
    {
        pointerEvent = data;
        previousPosition = null;
    }
    /// <summary>
    /// When the pointer is down, reset the scale event origin
    /// </summary>
    /// <param name="data">The pointer event data</param>
    public void OnPointerUp(PointerEventData data)
    {
        pointerEvent = null;
        previousPosition = null;
    }
    
    /// <summary>
    /// 
    /// </summary>
    public void OnMove(AxisEventData data)
    {
    }
}
