using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class UIHandleBinder : MonoBehaviour
{
    public static UIHandleBinder Instance;
    public bool BindingInProgress = false;
    public UIHandle TempHandle1;
    public UIHandle TempHandle2;
    /// <summary>[0]-child [1]-parent [2]-original parent</summary>
    public List<Binding> Bindings = new List<Binding>();

    private void Awake()
    {
        Instance = this;
    }

    public void StartBinding(UIHandle handle)
    {
        TempHandle1 = handle;
        BindingInProgress = true;
    }

    public void EndBinding(UIHandle handle)
    {
        TempHandle2 = handle;
        Binding row = Bindings.FirstOrDefault(b => b.Child == TempHandle1);
        if (row != null)
        {
            row.Parent = TempHandle2;
        }
        else
        {
            Bindings.Add(new Binding( TempHandle1, TempHandle2, TempHandle1.Owner.transform.parent));
        }
        TempHandle1.Owner.transform.SetParent(TempHandle2.Owner.transform);
        BindingInProgress = false;
    }

    public List<Binding> GetBindings(UIHandle handle)
    {
        return Bindings.Where(b => b.Child == handle || b.Parent == handle).ToList();
    }

    public bool Unparent(UIHandle handle)
    {
        var bindings = GetBindings(handle);
        if (bindings == null) return false;
        var binding = bindings.FirstOrDefault(b => b.Child == handle);
        if (binding == null) return false;
        handle.Owner.transform.SetParent(binding.OriginalParent);
        Bindings.Remove(binding);
        return true;
    }

    public class Binding{
        public UIHandle Child;
        public UIHandle Parent;
        public Transform OriginalParent;

        public Binding(UIHandle child, UIHandle parent, Transform origParent)
        {
            Child = child;
            Parent = parent;
            OriginalParent = origParent;
        }
    }
}
