class_name Chocolate
extends Node3D


const COLLECT_ANIM := "collection"
const COLLECT_DURATION := 2.0

@onready var chocolateAnimation: AnimationPlayer = $ChocolateAnimation
@onready var pickupSound: AudioStreamPlayer3D = $ChocolatePickupSound

var _collected := false


func _on_chocolate_tablet_body_entered(body: Node3D) -> void:
	if _collected:
		return

	if body is Walker:
		_give_chocolate_to(body)
	if body is SeatedVehicle:
		_give_chocolate_to_driver_of(body)


func _give_chocolate_to(walker: Walker) -> void:
	walker.give_chocolate()
	_go_to_pocket.call_deferred(walker)
	chocolateAnimation.play(COLLECT_ANIM)
	pickupSound.play()
	_collected = true


func _give_chocolate_to_driver_of(vehicle: SeatedVehicle) -> void:
	var driver = vehicle.get_current_driver()
	if driver == null:
		return

	_give_chocolate_to(driver)


func _go_to_pocket(walker: Walker) -> void:
	reparent(walker)
	var center_tween = create_tween()
	center_tween.tween_property(self, "position", walker.get_pocket_position(), COLLECT_DURATION)
	center_tween.tween_callback(queue_free)
