using Godot;
using Sfs3.Client.Entities;
using System;
using System.Collections.Generic;

public partial class GameList : VBoxContainer
{
	private Action<int, bool> joinGameAction;

	private readonly Dictionary<int, Node> itemNodes = [];

	public Action<int, bool> JoinGameAction
	{
		get => joinGameAction;
		set => joinGameAction = value;
    }

	public void PopulateList(IList<Room> rooms)
    {
        foreach (var room in rooms)
            AddListItem(room);
    }

	public void AddListItem(Room room)
	{
		// Show only game rooms
		// Also password protected Rooms are skipped, to make this example simpler
		// (protection would require an interface element to input the password)
		if (!room.IsGame || room.IsHidden || room.IsPasswordProtected)
			return;

		// Instantiate GameListItem and add to dictionary
		Node itemNode = ResourceLoader.Load<PackedScene>("res://scenes/sub/GameListItem.tscn").Instantiate();
		itemNodes.Add(room.Id, itemNode);

		// Init game list item and add to dictionary
		GameListItem item = GetListItem(room.Id);
		item.Init(room);

		// Add node to scene
		AddChild(itemNode);

		// Add listener to play button
		item.playButton.Pressed += () => { joinGameAction?.Invoke(room.Id, false); };
	}

	private GameListItem GetListItem(int id)
    {
        bool success = itemNodes.TryGetValue(id, out Node item);

		if (success)
			return item.GetNode<GameListItem>(".");
		else
			return null;
    }

	public void SetItemState(int roomId)
	{
		var item = GetListItem(roomId);

		if (item != null)
			item.Update();
	}
	
	public void RemoveListItem(int roomId)
    {
		bool success = itemNodes.TryGetValue(roomId, out Node item);

		if (success)
		{
			RemoveChild(item);

			itemNodes.Remove(roomId);
		}
    }
}
