using System;
using UnityEngine;
using UnityEngine.UIElements;

namespace KitsuneCafe.UI
{
  public class FixedLayout : ILayout
  {
    public FlowDirection Direction { get; set; } = FlowDirection.Vertical;
    public float ItemSize { get; set; }
    public float GutterSize { get; set; } = 0;
    public int Buffer { get; set; } = 0;
    public bool Wrap { get; set; } = false;

    public int Count { get; set; }
    public float ContentSize { get; private set; }

    public FixedLayout(FlowDirection direction, float itemSize, float gutterSize)
    {
      Direction = direction;
      ItemSize = itemSize;
      GutterSize = gutterSize;
    }

    public FixedLayout(FlowDirection direction, float itemSize) : this(direction, itemSize, 0) { }

    public float GetItemPosition(int index)
    {
      return index * (ItemSize + GutterSize);
    }

    public float GetItemSize(int _index)
    {
      return ItemSize;
    }

    public void Update(int itemCount, VisualElement _container)
    {
      Count = itemCount;
      ContentSize = itemCount * (ItemSize + GutterSize);
    }

    public Range GetVisibleRange(float offset, float containerSize)
    {
      var size = ItemSize + GutterSize;
      var halfBuffer = Mathf.CeilToInt(Buffer / 2);
      var first = Mathf.FloorToInt(offset / (ItemSize + GutterSize)) - halfBuffer;
      var count = Mathf.CeilToInt(containerSize / size) + halfBuffer;
      var last = Math.Min(Count, first + count);

      Debug.Log($"{first}:{last}");
      return new Range(first, last);
    }
  }
}
