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

public partial class Base : Area2D
{
	private ProgressBar _progressBar;
	public HealthComponent HealthComponent;

	private Node2D _selection;
	private Node2D _gfx;

	[Export]
	public bool Selected = false;

	[Export]
	public Faction Faction = Faction.Neutral;

	private float _buildSpeed = 28;
	private float _buildProgress = 0;
	private float _maxBuildProgress = 100;
	private bool _mouseInside = false;

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

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

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

		_selection.Visible = false;
		_progressBar.MaxValue = _maxBuildProgress;
		HealthComponent.MaxHealth = 100;
		HealthComponent.Health = 100;

		UpdateColor();
	}

	public override void _Process(double delta)
	{
		if (Faction == Faction.Neutral)
			return;

		_buildProgress += _buildSpeed * delta.ToFloat();
		if (_buildProgress >= _maxBuildProgress)
		{
			_buildProgress = 0;
			var pip = _pipScene.Instantiate<Pip>();

			GetParent().AddChild(pip);
			pip.Faction = Faction;
			pip.GlobalPosition = GlobalPosition;
			pip.Target = GetTree().GetFirstNodeInGroup("enemyBase") as Base;
		}

		UpdateProgressBars();
	}

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

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

	private void UpdateProgressBars()
	{
		_progressBar.Value = _buildProgress;
	}

	private void OnMouseExited()
	{
		_mouseInside = false;
	}

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