using System.Collections.Generic;
using Godot;

namespace Hellswipers.Game;

public partial class Icons : Node2D {
    private const int IconSize = 144;
    private const int SpaceBetween = 48;
    private const int TotalIconSize = IconSize + SpaceBetween;
    private const double AnimationLength = 0.4;
    private static readonly Vector2 IconScale = new(0.5625f, 0.5625f);

    private readonly Queue<Sprite2D> _icons = new();

    private Sprite2D CreateIcon(Texture2D tex) {
        var icon = new Sprite2D();
        icon.Texture = tex;
        icon.Scale = IconScale;
        AddChild(icon);
        _icons.Enqueue(icon);
        return icon;
    }

    public void Init(Gem[] nextGems) {
        CreateIcon(null);
        var pos = TotalIconSize;
        foreach (var gem in nextGems) {
            CreateIcon(gem.Texture).Position = new(pos, 0);
            pos += TotalIconSize;
        }
    }

    public void Update(Gem gem) {
        var tween = CreateTween();
        tween.SetParallel();
        tween.SetTrans(Tween.TransitionType.Cubic);
        tween.SetEase(Tween.EaseType.InOut);

        var oldIcon = _icons.Dequeue();
        tween.TweenProperty(oldIcon, "position:x", -Position.X - IconSize, AnimationLength);
        tween.TweenProperty(oldIcon, "self_modulate", new Color(1, 1, 1, 0), AnimationLength);

        var newIcon = CreateIcon(gem.Texture);
        newIcon.Position = new(_icons.Count * TotalIconSize, 0);
        newIcon.SelfModulate = new(1, 1, 1, 0);
        tween.TweenProperty(newIcon, "self_modulate", new Color(1, 1, 1, 1), AnimationLength);

        foreach (var icon in _icons)
            tween.TweenProperty(icon, "position:x", icon.Position.X - TotalIconSize, AnimationLength);

        tween.Finished += () => {
            RemoveChild(oldIcon);
            oldIcon.QueueFree();
        };
    }
}