using System;
using UnityEngine.UIElements;

namespace KitsuneCafe.UI.MVVM
{
  public class AdHocBinder : IBinder
  {
    private readonly Func<VisualElement> create;
    private readonly Action<VisualElement, int> bind;
    private readonly Action<VisualElement> unbind;
    private readonly Action<VisualElement> destroy;

    public AdHocBinder(
      Func<VisualElement> create,
      Action<VisualElement, int> bind,
      Action<VisualElement> unbind,
      Action<VisualElement> destroy
      )
    {
      this.create = create;
      this.bind = bind;
      this.unbind = unbind;
      this.destroy = destroy;
    }

    public AdHocBinder(
      Func<VisualElement> create,
      Action<VisualElement, int> bind,
      Action<VisualElement> unbind
      ) : this(create, bind, unbind, null)
    { }

    public AdHocBinder(
      Func<VisualElement> create,
      Action<VisualElement, int> bind
      ) : this(create, bind, null, null)
    { }

    public VisualElement CreateItem()
    {
      return create();
    }

    public void BindItem(VisualElement element, int index)
    {
      bind(element, index);
    }

    public void UnbindItem(VisualElement element)
    {
      if (unbind is not null)
      {
        unbind(element);
      }
    }

    public void DestroyItem(VisualElement element)
    {
      if (destroy is not null)
      {
        destroy(element);
      }
    }
  }
}
