extends Node3D

var load_place = preload("res://places/base_place/base_place.tscn")
var place = null

enum ROOM_BUILD_STATE {NONE, SELECT, DRAG, CONFIRM, PLACE}

#Tracks the current build state.
var room_build_state = 0

var current_room = null

var current_object = null

#Tracks the position that was first clicked to start a build drag
var build_drag_start_pos = null

signal room_built

func _on_child_entered_tree(node: Node) -> void:
	if node is Place:
		place = node

func _on_build_toggle(toggled_on):
#Enables construction of a room

	if toggled_on:
		room_build_state = ROOM_BUILD_STATE.SELECT
	else:
		place.clear_selection()
		room_build_state = ROOM_BUILD_STATE.NONE

func _on_confirm_button_pressed() -> void:
#Confirms the room that is currently being constructed

	if place.selection_dict:
		if room_build_state == ROOM_BUILD_STATE.SELECT:
			if place.build_confirm_allowed:
				place.build_selection()
				room_build_state = ROOM_BUILD_STATE.NONE
				
			else:
				prints("Building not allowed.")
	else:
		prints("Nothing selected.")

func _on_init_grid_button_pressed() -> void:
#TEMP: Responds to the grid initialization button

	if place:
		place.queue_free()
	var new_place = load_place.instantiate()
	add_child(new_place)
	place.init_grid()

func _on_door_button_pressed() -> void:
#Sets up door creation

	match room_build_state:
		ROOM_BUILD_STATE.NONE:
			current_object = "door"
			place.current_room = current_room
			place.init_object(current_object)
			room_build_state = ROOM_BUILD_STATE.PLACE
		_:
			return

func _on_worker_button_pressed() -> void:
#Sets up worker creation

	match room_build_state:
		ROOM_BUILD_STATE.NONE:
			current_object = "actor"
			place.init_object(current_object)
			room_build_state = ROOM_BUILD_STATE.PLACE

func _on_area_3d_input_event(_camera, _event, event_position, _normal, _shade_id):
#Checks input events from the mouse plane

	match room_build_state:
		ROOM_BUILD_STATE.SELECT:
			if Input.is_action_pressed("select"):
				room_build_state = ROOM_BUILD_STATE.DRAG
				build_drag_start_pos = event_position
				place.draw_tile_click(build_drag_start_pos)
	
		ROOM_BUILD_STATE.DRAG:
			if Input.is_action_pressed("select"):
				place.init_select_drag(build_drag_start_pos, event_position)
			else:
				room_build_state = ROOM_BUILD_STATE.SELECT
				place.end_select_drag()
			
		ROOM_BUILD_STATE.PLACE:
			if Input.is_action_pressed("select"):
				room_build_state = ROOM_BUILD_STATE.NONE
				place.confirm_object()
				emit_signal("room_built")
			else:
				place.hover_object(event_position)
