using System.Collections.Generic;
using Godot;

namespace NodeWar;

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

	public Nodule BuildingNodule { get; set; }

	public override void _Ready() { }

	[Export]
	private PackedScene _noduleScene;

	[Export]
	private PackedScene _rootScene;

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

	public override void _Process(double delta)
	{
		if (Input.IsActionJustPressed("build") && !Building)
		{
			Building = true;
			BuildingNodule = _noduleScene.Instantiate<Nodule>();
			BuildingNodule.BuildMode = true;

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

				// try connecting built nodule to connected ones
				foreach (var connectedNodule in BuildingNodule.ConnectedNodules)
				{
					RegisterConnection(BuildingNodule, connectedNodule);
				}

				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 = _rootScene.Instantiate<Root>();
			GetParent().AddChild(root);

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

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