using System.Linq;
using Godot;
using GodotSharp.SourceGenerators;
using GodotUtilities;

namespace NodeWar;

[Scene]
public partial class Root : Node2D
{
	[Node]
	private Line2D _line2D;

	private Nodule a;
	private Nodule b;

	public override void _Ready()
	{
		GD.Print(_line2D);
	}

	public void ConnectNodules(Nodule a, Nodule b)
	{
		this.a = a;
		this.b = b;

		GlobalPosition = a.GlobalPosition;
		GenerateLinePoints();
	}

	private void GenerateLinePoints()
	{
		var direction = b.GlobalPosition - a.GlobalPosition;
		var sectionLength = direction.Length() / 5;
		var points = new Vector2[5];

		for (var i = 0; i < 5; i++)
		{
			var randomOffset = new Vector2(MathUtil.RNG.Randf(), MathUtil.RNG.Randf());
			points[i] = i switch
			{
				0 => Vector2.Zero,
				4 => direction,
				_ => (direction.Normalized() + (randomOffset * 0.1f)).Normalized()
					* sectionLength
					* i,
			};
		}

		_line2D.Points = points;
	}

	public override void _Notification(int what)
	{
		if (what == NotificationSceneInstantiated)
		{
			WireNodes();
		}
	}
}
