using Godot;

/**
 * Base class of the objects moving in the game world: starships and weapon shots.
 *
 * Coordinates and speed are those of the server-side simulation (pixels, y axis pointing up),
 * while the node is placed in the world with the y axis flipped (see WorldPosition).
 */
public partial class GameItem : Node2D
{
	protected const string ANIM_EXPLODE = "explode";

	[Export]
	public AnimatedSprite2D sprite;

	public float xx;
	public float yy;

	// Current speed
	public Velocity velocity = new(0, 0);

	// Time of the last simulation step, in milliseconds
	public double lastRenderTime;

	private double destroyTimer = -1;

	/**
	 * Position of the item in the server coordinates system (y axis pointing up).
	 */
	public Vector2 WorldPosition
	{
		set => Position = new Vector2(value.X, -value.Y);
		get => new Vector2(Position.X, -Position.Y);
	}

	public override void _Process(double delta)
	{
		if (destroyTimer >= 0)
			destroyTimer += delta;

		if (destroyTimer > 1)
			QueueFree();
	}

	/**
	 * Show the explosion animation and remove the item as soon as the animation is over.
	 *
	 * If a position is passed, the item is moved and stopped there: this is the position where
	 * the server detected the collision, which can differ slightly from the simulated one.
	 */
	public virtual void Explode(Vector2? position = null)
	{
		// Activate the timer which gives the explosion animation enough time (one second)
		// to play before the node is removed (see _Process)
		destroyTimer = 0;

		if (position != null)
		{
			velocity = new Velocity(0, 0);
			WorldPosition = (Vector2)position;
		}

		sprite.Play(ANIM_EXPLODE);
	}
}
