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

public partial class Battle : Node
{
	[Signal]
	public delegate void SetCurrentEventHandler(Battle BATTLE);
	//[Signal]
	//public delegate void DetectMovementEventHandler(bool BOOL);
	
	public bool _current;
	public Vector2 _startPosition = new Vector2(890, 340);
	public Player _player;
	public List<Sprite2D> _potted = new();
	public List<Ball> _balls;
	
	
	public override void _Ready()
	{
		_player = GetNode<Player>("Player");
		Start();
		
		List<Area2D> pockets = GetNode<Table>("Table").GetChildren()
			.Where(n => n.GetName().ToString().ToLower().Contains("pocket"))
			.Select(n => (Area2D)n)
			.ToList<Area2D>();
		for (int i = 0; i < pockets.Count; i++)
		{
			pockets[i].BodyEntered += PottedBall;
		}
		_balls = GetTree().GetNodesInGroup("balls").Select(b => (Ball)b).ToList<Ball>();
	}
	
	public override void _Process(double DELTA_)
	{
		CheckMovement();
	}
	
	public void GenerateBalls()
	{
		int count = 1;
		int rows = 5;
		int diameter = 36;
		for (int i = 0; i < 5; i++)
		{
			for (int j = 0; j < rows; j++)
			{
				Vector2 position = new Vector2(250 + (i*(diameter)), 267 + (j*(diameter)) + (i*(diameter / 2)));
				Ball ball = Ball.Create("ball", count);
				ball.Place(position);
				AddChild(ball);
				
				count += 1;
			}
			rows -= 1;
		
		}
	}
	
	public void CheckMovement()
	{
		bool movementCheck = _balls.Any(b => b._moving && b._placed);
		if (movementCheck)
		{
			if (!Globals.Instance._anyMovement)
			{
				Globals.Instance._anyMovement = true;
				//EmitSignal(SignalName.DetectMovement, true);

			}
		}
		else
		{
			if (Globals.Instance._anyMovement)
			{
				Globals.Instance._anyMovement = false;
				//EmitSignal(SignalName.DetectMovement, false);
			}
		}
	}
	
	public void PottedBall(Node2D BODY)
	{
		if (BODY.GetType() != typeof(Ball)){
			return;
		}
		if (BODY == _player._actor._activeBall)
		{
			GD.Print(1);
			_player._actor._activeBall._potted = true;
			_player._actor._activeBall._placed = false;
		}
		else
		{
			GD.Print(BODY);
			Sprite2D ballSprite = new Sprite2D();
			AddChild(ballSprite);
			ballSprite.Texture = BODY.GetNode<Sprite2D>("Image").Texture;
			_potted.Add(ballSprite);
			ballSprite.Position = new Vector2(50 * _potted.Count, 725);
			((Ball)BODY)._placed = false;
			((Ball)BODY)._potted = true;
			BODY.QueueFree();
		}
	}
	
	public void Start()
	{
		_current = true;
		GenerateBalls();
		
		EmitSignal(SignalName.SetCurrent, this);
	}

}
