using Godot;
using System;
using System.Linq;
using Cirno.Scripts;
using GTweens.Builders;
using GTweens.Easings;
using GTweens.Tweens;
using GTweensGodot.Extensions;
using Cirno.Scripts.Resources;

public partial class AudioNameVisualizer : AudioStreamPlayer2D
{
    [Export]
    public MusicResource MusicData { get; set; }

    [Export] public PackedScene CanvasTemplate;

    private MusicVisualizerCanvas _canvasLayer;

    public override void _Ready()
    {
        Setup();

        if (Autoplay)
        {
            PlayWithName();
        }
    }

    private void Setup()
    {
        if (MusicData?.Track is not null)
        {
            this.Stream = MusicData.Track;
        }

        var existingCanvas = this.GetTree().Root.GetNodeOrNull<CanvasLayer>("AudioCanvas");

        if (existingCanvas is null)
        {
            // _canvasLayer = new CanvasLayer();
            // _canvasLayer.Name = "AudioCanvas";
            _canvasLayer = CanvasTemplate.Instantiate<MusicVisualizerCanvas>();
            GetTree().Root.CallDeferred("add_child", _canvasLayer);
        }
        else
        {
            _canvasLayer = (MusicVisualizerCanvas)existingCanvas;
        }
    }

    public void PlayWithName()
    {
        ShowName();
        Play();
    }

    public void ShowName()
    {
        if (MusicData is null)
        {
            GD.PushWarning("Music data was null");
            return;
        }
        _canvasLayer.ShowName(MusicData.TrackName, MusicData.ShowAuthor ? MusicData.AuthorName : null);
    }
}
