using System;
using Godot;
using NodeWar.scripts.components;

namespace NodeWar.scripts;

public partial class Base : Area2D
{
	private Node2D _selection;
	private Node2D _gfx;

	public Vector2 TargetPosition { get; set; }

	[Export]
	public Node2D Target;

	[Export]
	public HealthComponent HealthComponent;

	[Export]
	public SpawnerComponent SpawnerComponent;

	[Export]
	public bool Selected = false;

	[Export]
	public Faction Faction = Faction.Neutral;

	private bool _mouseInside = false;
	private bool _selected = false;

	private PackedScene _pipScene = GD.Load<PackedScene>("res://pip.tscn");

	public override void _Ready()
	{
		MouseEntered += OnMouseEntered;
		MouseExited += OnMouseExited;

		_selection = GetNode<Node2D>("Selection");
		_gfx = GetNode<Node2D>("Gfx");

		_selection.Visible = false;
		SpawnerComponent.Faction = Faction;

		UpdateColor();
	}

	public override void _UnhandledInput(InputEvent @event)
	{
		if (@event is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left })
		{
			_selected = _mouseInside;

			if (_selected)
			{
				_selection.Visible = true;

				// TODO: super ugly
				EventBus.Instance.EmitSignal(
					EventBus.SignalName.SelectionChanged,
					"This is a Base"
				);
			}
			else
			{
				_selection.Visible = false;
			}
		}

		if (
			@event is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Right }
			&& _selected
		)
		{
			// TODO: 3 Stellen eine Sache zu speichern?
			TargetPosition = GetGlobalMousePosition();
			Target.GlobalPosition = TargetPosition;
			SpawnerComponent.Target = TargetPosition;
		}
	}

	private void UpdateColor()
	{
		_gfx.Modulate = Faction switch
		{
			Faction.Neutral => Colors.Gray,
			Faction.Player => Colors.ForestGreen,
			Faction.Computer => Colors.Red,
			_ => throw new ArgumentOutOfRangeException(),
		};
	}

	private void OnMouseExited()
	{
		_mouseInside = false;
	}

	private void OnMouseEntered()
	{
		_mouseInside = true;
	}
}
