using Godot;
using System.Linq;
using System.Collections.Generic;

public partial class DebugZombieSpawner : PopupPanel
{
	private List<string> variants;
	[Export] private Label label;
	[Export] private LineEdit line;
	[Export] private SpinBox spin;

	public void OnTextChanged(string text)
	{
		variants = GameRegistry.GetZombieNames();
		variants.Sort(Comparer);

		if (variants.Count > 3)
		{
			label.Text = $"{variants[0]}\n{variants[1]}\n{variants[2]}";
		}
		else
		{
			label.Text = "";
			for (int i = 0; i < variants.Count; i++)
			{
				label.Text += variants[i] + "\n";
			}
		}
	}
	public void OnTextSubmitted(string text)
	{
		spin.GrabFocus();
	}
	public void OnPopupHide()
	{
		if (variants == null || variants.Count == 0)
		{
			return;
		}
		ZombieSequencer.Instance.DebugClearQueue();
		for(int i = 0; i < spin.Value; i++)
		{
			ZombieSequencer.Instance.Add(variants[0]);
		}

		QueueFree();
	}
	private int Comparer(string x, string y)
	{
		return LevensteinDistance(x,line.Text) - LevensteinDistance(y,line.Text);
	}
	private static int LevensteinDistance(string a, string b)
	{
		if (b.Length == 0)
		{
			return a.Length;
		}
		else if (a.Length == 0)
		{
			return b.Length;
		}
		else if (a[0] == b[0])
		{
			return LevensteinDistance(a[1..], b[1..]);
		}
		List<int> x = [LevensteinDistance(a[1..], b[1..]), LevensteinDistance(a[1..], b), LevensteinDistance(a, b[1..])];
		return 1 + x.Min();
	}
}
