extends Node3D

signal cleaned
signal activated

const CLEAN_THRESHOLD := 1400

@export var clean := false
@export var enabled := false

@onready var animation_player: AnimationPlayer = %AnimationPlayer
@onready var light_animation: AnimationPlayer = %LightAnimation
@onready var gunk_body: GunkBody = %GunkBody
@onready var interactive: Interactive = %Interactive

# XXX I must have been smoking crack when I wrote this logic. Why so complicated?


func _ready() -> void:
	if clean:
		gunk_body.clear_all()
		_on_clean()
	if enabled:
		_on_enable()


## Called once all gunk is cleared. Enables interaction & plays animations
func enable() -> void:
	enabled = true
	_on_enable()


func _on_enable() -> void:
	if clean:
		light_animation.play("success")
		if not animation_player.is_playing():
			interactive.enabled = true


## Called once the switch is no longer usable. Disables interaction & plays animations
func disable() -> void:
	_on_disable()
	enabled = false


func _on_disable() -> void:
	if enabled and clean:
		light_animation.play("disable")
	else:
		light_animation.play("RESET")
	interactive.enabled = false


func _on_clean() -> void:
	clean = true
	if enabled:
		_on_enable()
	else:
		_on_disable()
	cleaned.emit()


func _activate() -> void:
	animation_player.play("activate")
	activated.emit()
	# Disable while animation is playing
	interactive.enabled = false


func _animation_finished(anim_name: StringName) -> void:
	if anim_name == "activate":
		interactive.enabled = enabled


func _on_gunk_body_clear_total_updated(clear_total: float) -> void:
	if not clean and clear_total >= CLEAN_THRESHOLD:
		_on_clean()
