using Godot;

namespace NodeWar;

[SceneTree]
public partial class ConnectionArea : Area2D
{
	[Signal]
	public delegate void NoduleEnteredEventHandler(Nodule nodule);

	[Signal]
	public delegate void NoduleExitedEventHandler(Nodule nodule);

	public override void _Ready()
	{
		AreaEntered += OnAreaEntered;
		AreaExited += OnAreaExited;
	}

	private void OnAreaEntered(Area2D area)
	{
		switch (area)
		{
			case Nodule nodule:
				HandleNoduleEntered(nodule);
				break;
			case ConnectionArea connectionArea:
				HandleNoduleEntered(connectionArea.GetParent() as Nodule);
				break;
		}

		return;

		void HandleNoduleEntered(Nodule newNodule)
		{
			if (newNodule.BuildMode)
			{
				return;
			}

			EmitSignalNoduleEntered(newNodule);
		}
	}

	private void OnAreaExited(Area2D area)
	{
		switch (area)
		{
			case Nodule nodule:
				HandleNoduleExited(nodule);
				break;
			case ConnectionArea connectionArea:
				HandleNoduleExited(connectionArea.GetParent() as Nodule);
				break;
		}

		return;

		void HandleNoduleExited(Nodule newNodule)
		{
			if (newNodule.BuildMode)
			{
				return;
			}

			EmitSignalNoduleExited(newNodule);
		}
	}
}
