extends Node


# Declare member variables here. Examples:
# var a = 2
# var b = "text"
var door_list = {}

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

func register_door(obj: Node, name, door_obj, axis, cangle, oangle, spd):
	assert(obj)
	assert(door_obj)
	var root_name = str(obj.get_path())
	if !door_list.has(root_name):
		door_list[root_name] = {}
	var base = door_obj.transform
	door_list[root_name][name] = {}
	door_list[root_name][name].obj = door_obj
	door_list[root_name][name].base = base
	door_list[root_name][name].axis = axis
	door_list[root_name][name].cangle = cangle
	door_list[root_name][name].oangle = oangle
	door_list[root_name][name].cur_angle = cangle
	door_list[root_name][name].speed = spd
	door_list[root_name][name].active = false
	door_list[root_name][name].state = 0
func open_door(obj, name):
	var root_name = str(obj.get_path())
	if !door_list.has(root_name):
		return
	door_list[root_name][name].active = true
	door_list[root_name][name].state = 1
func close_door(obj, name):
	var root_name = str(obj.get_path())
	if !door_list.has(root_name):
		return
	door_list[root_name][name].active = true
	door_list[root_name][name].state = 0
func is_active(obj, name):
	var root_name = str(obj.get_path())
	if !door_list.has(root_name):
		return false
	return door_list[root_name][name].active
func get_state(obj, name):
	var root_name = str(obj.get_path())
	if !door_list.has(root_name):
		return -1
	return door_list[root_name][name].state
func _process(delta):
	for e in door_list.keys():
		for j in door_list[e].keys():
			var m = door_list[e][j]
			if m.active:
				var change = min(1.0, m.speed * delta)
				match m.state:
					0:
						if abs(m.cur_angle - m.cangle) < 0.001:
							m.cur_angle = m.cangle
							m.active = false
						else:
							m.cur_angle = lerp_angle(m.cur_angle, m.cangle, change)
					1:
						if abs(m.cur_angle - m.oangle) < 0.001:
							m.cur_angle = m.oangle
							m.active = false
						else:
							m.cur_angle = lerp_angle(m.cur_angle, m.oangle, change)
				m.obj.transform.basis = m.base.basis.rotated(m.axis, m.cur_angle)
				
