extends Reference

const NAME = "interacting"

var ctx: KinematicBody = null
var anim_tree: AnimationTree
var timer: SceneTreeTimer

func _init():
	pass

func enter_from(state):
	anim_tree = ctx.get_node("model_transform/DungMan/AnimationTree")
	anim_tree["parameters/Move/playback"].travel("idle")
	anim_tree["parameters/Activate/active"] = true
	timer = ctx.get_tree().create_timer(0.2)
	timer.connect("timeout", self, "_on_timeout", [], CONNECT_ONESHOT)

func exit_to(state):
	pass

func physics_process(delta):
	pass

func unhandled_input(event):
	pass

func _on_timeout():
	for area in ctx.get_node("%TriggerVolume").get_overlapping_areas():
		if try_trigger_interact(area):
			break
	if ctx.state == self:
		ctx.change_state(ctx.StateDefault.new())

func try_trigger_interact(area) -> bool:
	var owner = area
	if area.has_meta("owner"):
		owner = area.get_meta("owner")
	
	if not owner.has_method("on_player_interact"):
		return false
		
	var result = owner.on_player_interact(ctx)

	if not result:
		print("player failed to interacted with ", owner)
		return false

	print("player interacted with ", owner)
	return true

func on_sleep(made_it_to_bed: bool, hop_position: Spatial):
	timer.disconnect("timeout", self, "_on_timeout")
	ctx.change_state(ctx.StateSleeping.new(made_it_to_bed, hop_position))
