using UnityEngine;
using UnityEngine.EventSystems;

public class UIDraggableProxy : MonoBehaviour, IEndDragHandler, IDragHandler
{
    public bool InitializeOnAwake;
    public UIElementDragger Draggable;
    public TMPro.TMP_Text Label;

    public static UIDraggableProxy Create(Transform parent)
    {
        var proxy = Instantiate(SharedResources.Instance.UIDraggableProxy, parent);
        return proxy;
    }

    private void Awake()
    {
        if (InitializeOnAwake)
        {
            Link(Draggable);
        }
    }

    public UIDraggableProxy Link(UIElementDragger obj)
    {
        Label.text = string.IsNullOrEmpty(obj.ProxyName)? obj.name : obj.ProxyName;
        Draggable = obj;
        obj.SetProxyMode(this);
        obj.ProxySetVisible(false);
        return this;
    }

    public void OnDrag(PointerEventData eventData)
    {
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (Draggable.LockProxyState) return;
        Draggable.SetProxyMode(null);
        Draggable.transform.position = Input.mousePosition;
        Destroy(this.gameObject);
    }

    public void ToggleDraggableVisible()
    {
        CloseSiblingProxies();
        Draggable.ProxySetVisible(!Draggable.gameObject.activeSelf);
    }

    public void SetDraggableVisible(bool visible)
    {
        if (visible)
        {
            CloseSiblingProxies();
        }
        Draggable.ProxySetVisible(visible);
    }

    private void CloseSiblingProxies()
    {
        var toolbar = GetComponentInParent<UIToolbar>();
        var siblings = toolbar.GetComponentsInChildren<UIDraggableProxy>();
        foreach (var sibling in siblings)
        {
            if (sibling.gameObject != this.gameObject)
            {
                sibling.Draggable.ProxySetVisible(false);
            }
        }
    }
}
