using System.Collections.Generic;
using Godot;

namespace NodeWar;

public partial class BuildManager : Node
{
	private bool Building { get; set; }

	private Nodule BuildingNodule { get; set; }

	private Dictionary<NoduleConnection, Root> NoduleConnections { get; set; } = new();

	public static BuildManager Instance { get; private set; }

	public override void _Ready()
	{
		Instance = this;
	}

	public override void _Process(double delta)
	{
		if (Input.IsActionJustPressed(MyInput.Build) && !Building)
		{
			StartBuilding();
		}
	}

	private void StartBuilding()
	{
		BuildingNodule = Instantiator.Instantiate<Nodule>();

		Building = true;
		BuildingNodule.BuildMode = true;

		BuildingNodule.NoduleBuilt += () =>
		{
			Building = false;
			BuildingNodule = null;
		};

		BuildingNodule.BuildingCanceled += () =>
		{
			Building = false;
			BuildingNodule = null;
		};

		GetParent().AddChild(BuildingNodule);
	}

	public void RegisterConnection(Nodule a, Nodule b)
	{
		if (!NoduleConnections.ContainsKey(new NoduleConnection { A = a, B = b }))
		{
			var root = Instantiator.Instantiate<Root>();
			GetParent().AddChild(root);

			root.ConnectNodules(a, b);
			root.GlobalPosition = a.GlobalPosition;

			NoduleConnections.Add(new NoduleConnection { A = a, B = b }, root);
		}
	}
}
