using Godot;
using SessionZero.SzfLib.Objects;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SessionZeroApp;

public partial class CustomListView : VBoxContainer
{
    [Export] private PackedScene _customListViewItemScene;

    private List<CustomListViewItem> _items = [];

    public bool AddItem(string guid, string itemName, string szfType, string version, Action viewAction, Action editAction, Action deleteAction)
    {
        if (_items.Any(item => item.Guid == guid))
        {
            GD.PrintErr($"CustomListView tried to add an item ({itemName}) with Guid `{guid}` but it already contains an item with that Guid");
            return false;
        }

        try
        {
            var newItem = _customListViewItemScene.Instantiate<CustomListViewItem>();
            _items.Add(newItem);
            AddChild(newItem);

            newItem.SetupItem(guid, itemName, szfType, version, viewAction, editAction, deleteAction);

            return true;
        }
        
        catch (InvalidCastException e)
        {
            GD.PrintErr($"Couldn't cast scene as CustomListViewItem: {e}");
        }

        return false;
    }

    public bool RemoveItem(string guid)
    {
        var item = _items.Where(i => i.Guid == guid).FirstOrDefault();
        if (item is null)
        {
            return false;
        }

        _items.Remove(item);
        item.QueueFree();

        return true;
    }
}
