using System;
using Godot;

namespace KarrotStarterTemplate.Common.AnimNotifies;

[GlobalClass]
public partial class AnimNotify : Node
{
	// Called when the node enters the scene tree for the first time.
	[Export] public AnimationMixer animationPlayer { get; set; }
	[Export] public AnimationTree animationTree { get; set; }
    
	public Action<string, string> AnimationNotify;

	public override void _Ready()
	{
		if (animationPlayer != null)
		{
			animationPlayer.AnimationStarted += OnAnimationStarted;
			animationPlayer.AnimationFinished += OnAnimationFinished;
		}
        
		if (animationTree != null)
		{
			animationTree.AnimationStarted += OnAnimationStarted;
			animationTree.AnimationFinished += OnAnimationFinished;
		}
	}



	public override void _ExitTree()
	{
		if (animationPlayer != null)
		{
			animationPlayer.AnimationStarted -= OnAnimationStarted;
			animationPlayer.AnimationFinished -= OnAnimationFinished;
		}
        
		if (animationTree != null)
		{
			animationTree.AnimationStarted -= OnAnimationStarted;
			animationTree.AnimationFinished -= OnAnimationFinished;
		}
	}

	private void OnAnimationFinished(StringName animname)
	{
		Notify("_" + animname, "finish");
	}
    
	private void OnAnimationStarted(StringName animname)
	{
		Notify("_" + animname, "start");
	}

	public void Notify(string id, string action)
	{
		AnimationNotify?.Invoke(id, action);
	}
}