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

public partial class StageGUI : Control
{
   [Signal]
   public delegate void OnCharacterSelectionMadeEventHandler(Character player);
   [Signal]
   public delegate void CapricornSelectedEventHandler(Player player);
   [Signal]
   public delegate void PiscesSelectedEventHandler(Player player);
   [Signal]
   public delegate void SagittariusSelectedEventHandler(Player player);
   [Signal]
   public delegate void ScorpioSelectedEventHandler(Player player);
   [Signal]
   public delegate void OnPlayerGameOverEventHandler(Player player);
   [Signal]
   public delegate void OnGameOverEventHandler(Array<Player> players);

   [Export]
   private AudioStreamPlayer _audioStreamPlayer;

   private GameManager _gameManager;

   public override void _Ready()
   {
	  _gameManager = GetTree().Root.GetNode<GameManager>("Main/GameManager");
   }

   public void OnCharacterSelect(Player player)
   {
	  if (player.GameOver)
		 return;

	  player.IsSelectingCharacter = true;
	  ChangeBG(player);
   }

   public override void _Input(InputEvent @event)
   {
	  var playersSelecting = _gameManager.Players.Where(x => x.IsSelectingCharacter);
	  foreach (var player in playersSelecting)
	  {
		 if (Input.IsActionJustPressed(player.PlayerInput.Right()))
		 {
			_gameManager.SetToNextCharacter(player);
			ChangeBG(player);
		 }
		 if (Input.IsActionJustPressed(player.PlayerInput.Left()))
		 {
			_gameManager.SetToPreviousCharacter(player);
			ChangeBG(player);
		 }

		 if (Input.IsActionJustPressed(player.PlayerInput.Fire()))
		 {
			GD.Print("Selected character");
			player.IsSelectingCharacter = false;
			EmitSignal(SignalName.OnCharacterSelectionMade, player);
			GetTree().Paused = false;
			if (_audioStreamPlayer != null)
			   _audioStreamPlayer.Play();
		 }
	  }

	  foreach (var player in _gameManager.Players)
	  {
		 if (player.GameOver)
			EmitSignal(SignalName.OnPlayerGameOver, player);
	  }

	  if (!_gameManager.IsGameOverScreenOn && _gameManager.Players.All(x => x.GameOver))
	  {
		 EmitSignal(SignalName.OnGameOver, new Array<Player>(_gameManager.Players));
	  }
   }

   private void ChangeBG(Player player)
   {
	  var instance = player.CharactersLeftOnStage.ElementAt(player.CharacterIndex).Instantiate();
	  var name = instance.Name;
	  GD.Print(name);
	  switch (name)
	  {
		 case "Capricorn":
			EmitSignal(SignalName.CapricornSelected, player);
			break;
		 case "Scorpio":
			EmitSignal(SignalName.ScorpioSelected, player);
			break;
		 case "Pisces":
			EmitSignal(SignalName.PiscesSelected, player);
			break;
		 case "Sagittarius":
			EmitSignal(SignalName.SagittariusSelected, player);
			break;
	  }
   }
}
