using System.Collections.Generic;
using Godot;
using Newlon;
using Newlon.Components.Level;
using Newlon.Components.Zombies;

public partial class ZombieSequencer : Node2D
{
	public static ZombieSequencer Instance { get; private set; }
	private Queue<string> queue = [];
	private RandomNumberGenerator rng = new();
	private bool turbo = false;

	[Export] private Timer spawnTimer;
	[Export] private Timer waveTimer;

	private double startSpawnTime;

	public override void _Ready()
	{
		rng.Randomize();
		Instance = this;
		startSpawnTime = spawnTimer.WaitTime;
	}


	private void FormSquad()
	{
		if (queue.Count == 0) return;
		int count = rng.RandiRange(1, queue.Count > 5 ? 5 : queue.Count);

		if (count == 5)
		{
			Spawn(queue.Dequeue(), 1);
			Spawn(queue.Dequeue(), 2);
			Spawn(queue.Dequeue(), 3);
			Spawn(queue.Dequeue(), 4);
			Spawn(queue.Dequeue(), 5);
		}

		List<int> list = [];
		while (list.Count < count)
		{
			int lane = rng.RandiRange(1, 5);
			if (list.Contains(lane) == true)
			{
				continue;
			}
			list.Add(lane);
		}

		foreach (int lane in list)
		{
			if (queue.Count > 0)
				Spawn(queue.Dequeue(), lane);
		}
	}

	private void Spawn(string id, int lane)
	{
		RuntimeZombieData zombie = GameRegistry.GetZombieByName(id).Scene.Instantiate<RuntimeZombieData>();
		PoolContainer.Instance.Zombies.AddChild(zombie);

		zombie.GlobalPosition = new Vector2(GlobalPosition.X, Utility.RightFieldBoundary.Y - (lane - 1) * Utility.TileHeight);
	}

	public void Add(string id)
	{
		queue.Enqueue(id);
	}

	public override void _Process(double delta)
	{
		if (turbo == false && queue.Count > waveTimer.WaitTime / startSpawnTime * 5.0)
		{
			spawnTimer.WaitTime = waveTimer.WaitTime / queue.Count;
			turbo = true;
		}
		else if(turbo && queue.Count == 0)
		{
			spawnTimer.WaitTime = startSpawnTime;
			turbo = false;
		}
	}

	public void DebugClearQueue()
	{
		queue.Clear();
	}
}
