@tool
@icon("res://addons/AnimatedTextureRect/AnimatedTextureRect.png")
extends TextureRect
class_name AnimatedTextureRect

@export var Frames: SpriteFrames = null
var _previous_frames: SpriteFrames = null
var _current_animation: StringName = "default"
var autoplay: StringName = ""
var _current_frame: int
var _frame_timer: float = 0.0
var _animation_stopped: bool = false

# Signals
signal animation_finished
signal animation_changed
signal animation_looped
signal frame_changed
signal sprite_frames_changed

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if !is_instance_valid(Frames): return
	
	_frame_timer += delta
	
	if Frames != _previous_frames:
		sprite_frames_changed.emit()
		_sprite_frames_changed()
	
	var frame_FPS: float = 1.0 / Frames.get_animation_speed(_current_animation)
	var frame_delay: float = frame_FPS * Frames.get_frame_duration(_current_animation, _current_frame)
	
	if !_animation_stopped:
		if _frame_timer > frame_delay:
			_frame_timer -= frame_delay
			_current_frame += 1
			frame_changed.emit()
			if _current_frame >= Frames.get_frame_count(_current_animation):
				if Frames.get_animation_loop(_current_animation):
					_current_frame = 0
					animation_looped.emit()
				else:
					_current_frame -= 1
					_animation_stopped = true
					animation_finished.emit()
	
	texture = Frames.get_frame_texture(_current_animation, _current_frame)

func play(animation: StringName) -> void:
	for _names in Frames.get_animation_names():
		if animation == _names:
			if _current_animation != animation: animation_changed.emit()
			_current_animation = animation
			_animation_stopped = false
			return

func stop() -> void:
	_animation_stopped = true
	_frame_timer = 0.0

@warning_ignore("native_method_override")
func get_class() -> String:
	return "AnimatedTextureRect"

func _sprite_frames_changed() -> void:
	if autoplay != "":
		_current_animation = autoplay
	else:
		if is_instance_valid(Frames):
			# Default to the first animation in the list
			_current_animation = Frames.get_animation_names()[0]
		else:
			_current_animation = "default"
