@tool
class_name BallSelector extends Control

const TWEEN_TIME := 0.2

const Y_OFFSET := {
	GameBall.Type.NONE: 50,
	GameBall.Type.BASIC: 18,
	GameBall.Type.PLASMA: -14,
	GameBall.Type.BRICK: -46,
	GameBall.Type.BEACH: -78,
	GameBall.Type.POWER: -110,
}

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

@onready var ball_list: VBoxContainer = %BallList
@onready var basic_icon: BallIcon = %BasicIcon
@onready var plasma_icon: BallIcon = %PlasmaIcon
@onready var brick_icon: BallIcon = %BrickIcon
@onready var beach_icon: BallIcon = %BeachIcon
@onready var power_icon: BallIcon = %PowerIcon


func _ready() -> void:
	value = value


## Set ball quantities based on player's state
func set_state_for_player(player: WorldPlayer) -> void:
	basic_icon.quantity = player.get_balls(GameBall.Type.BASIC)
	plasma_icon.quantity = player.get_balls(GameBall.Type.PLASMA)
	brick_icon.quantity = player.get_balls(GameBall.Type.BRICK)
	beach_icon.quantity = player.get_balls(GameBall.Type.BEACH)
	power_icon.quantity = player.get_balls(GameBall.Type.POWER)
	if player.shot_setup:
		value = player.shot_setup.ball_type
	player.on_balls_changed.connect(_set_quantity)


func _get_icon(type: GameBall.Type) -> BallIcon:
	match type:
		GameBall.Type.BASIC:
			return basic_icon
		GameBall.Type.PLASMA:
			return plasma_icon
		GameBall.Type.BRICK:
			return brick_icon
		GameBall.Type.BEACH:
			return beach_icon
		GameBall.Type.POWER:
			return power_icon
	return null


func _set_value(new_value: GameBall.Type) -> void:
	if not ball_list:
		return

	var tween := get_tree().create_tween()
	tween.tween_property(ball_list, "position:y", Y_OFFSET[new_value], TWEEN_TIME).set_trans(
		Tween.TRANS_EXPO
	)
	value = new_value


func _set_quantity(type: GameBall.Type, new_value: int) -> void:
	_get_icon(type).quantity = new_value
