@tool
class_name ClubSelector extends Control

const UNSELECTED_SCALE := Vector2(0.618, 0.618)
const SELECTED_SCALE := Vector2(1.0, 1.0)

const LABEL_SCALE_TIME := 0.3
const HUB_ROTATION_TIME := 0.2

const CLUB_ROTATION := {
	Club.Type.DRIVER: 0.0,
	Club.Type.IRON: -16.0,
	Club.Type.WEDGE: -32.0,
	Club.Type.SPECIAL: -48.0,
	Club.Type.PUTTER: -64.0,
}

@export var value: Club.Type:
	set = _set_value

@onready var club_hub: Control = %ClubHub

@onready var driver_label: ClubSelectorLabel = %DriverLabel
@onready var iron_label: ClubSelectorLabel = %IronLabel
@onready var wedge_label: ClubSelectorLabel = %WedgeLabel
@onready var special_label: ClubSelectorLabel = %SpecialLabel
@onready var putter_label: ClubSelectorLabel = %PutterLabel


## Enable/disable labels based on the player's available equipment
func set_state_for_player(player: WorldPlayer) -> void:
	driver_label.set_enabled(player.driver != null)
	iron_label.set_enabled(player.iron != null)
	wedge_label.set_enabled(player.wedge != null)
	special_label.set_enabled(player.special != null)
	putter_label.set_enabled(player.putter != null)
	if player.shot_setup:
		value = player.shot_setup.club_type


func _get_club_label(club: Club.Type) -> Label:
	match club:
		Club.Type.DRIVER:
			return driver_label
		Club.Type.IRON:
			return iron_label
		Club.Type.WEDGE:
			return wedge_label
		Club.Type.SPECIAL:
			return special_label
		Club.Type.PUTTER:
			return putter_label
	print_debug("Unknown club: ", club)
	return null


func _reset_label_scale() -> void:
	for c: Control in club_hub.get_children():
		c.scale = UNSELECTED_SCALE


func _set_value(new_value: Club.Type) -> void:
	var old_label := _get_club_label(value)
	var new_label := _get_club_label(new_value)
	value = new_value
	if not (old_label or new_label):
		return

	var tween := get_tree().create_tween()
	tween.set_parallel()

	if old_label:
		tween.tween_property(old_label, "scale", UNSELECTED_SCALE, LABEL_SCALE_TIME).set_trans(
			Tween.TRANS_SINE
		)

	if new_label:
		tween.tween_property(new_label, "scale", SELECTED_SCALE, LABEL_SCALE_TIME).set_trans(
			Tween.TRANS_SINE
		)
		var theta: float = CLUB_ROTATION[new_value]
		tween.tween_property(club_hub, "rotation_degrees", theta, HUB_ROTATION_TIME).set_trans(
			Tween.TRANS_QUAD
		)
