class_name Show
extends Node2D
# Manage slide cycling


signal new_focus(pos: Vector2, scale: float)

const VOID_SLIDE_ID := -1

@export var start_slide := 0

var current_id := VOID_SLIDE_ID
var current_slide: Slide

@onready var slides: Array = get_children()


func _ready():
	_enforce()
	next_slide()


func next_slide():
	_disconnect_current_slide()
	current_id = _next_id()
	current_slide = focus_slide(current_id)
	_connect_current_slide()


func focus_slide(id: int) -> Slide:
	var slide: Slide = slides[id]
	new_focus.emit(slide.get_position(), slide.get_scale().x)
	return slide


func _disconnect_current_slide():
	if current_slide != null:
		current_slide.finished.disconnect(_on_current_slide_finished)


func _connect_current_slide():
	current_slide.finished.connect(_on_current_slide_finished)


func _enforce() -> void:
	_enforce_parameters()
	_enforce_children()


func _enforce_parameters() -> void:
	assert(start_slide >= 0,
		"Negative index is not supported for start_slide")
	assert(start_slide < slides.size(),
		"start_slide index is out of bound (max is %s)" % (slides.size() - 1))


func _enforce_children() -> void:
	assert(!slides.is_empty(), "A slideshow must contain slides")
	for slide in slides:
		assert(slide is Slide, "A slideshow can only contain slides")


func _next_id() -> int:
	if current_id == VOID_SLIDE_ID:
		return start_slide

	var next_id: int = current_id + 1

	if next_id >= slides.size():
		return 0

	return next_id


func _on_current_slide_finished():
	next_slide()
