class_name Level extends Node3D

const player_controller = preload("res://templates/singleplayer_pc.tscn")
const trap_template = preload("res://templates/trap.tscn")

@onready var floor_layer : GridMap = %Floor
@onready var ramp_layer : GridMap = %Ramps
@onready var marker_layer : GridMap = %Markers

@export var difficulty : int = 1

var traps : Dictionary[Vector3i, Trap] = {}

func _ready() -> void:
	Game.level = self
	var player = player_controller.instantiate()
	var traps : Array[PlayerData.TrapData] = [
		PlayerData.TrapData.new(Trap.Type.FORCE_PANEL, 3, 3),
		PlayerData.TrapData.new(Trap.Type.BOMB, 3, 3),
		PlayerData.TrapData.new(Trap.Type.SWITCH, 3, 3),
		PlayerData.TrapData.new(Trap.Type.MINE, 3, 3),
		PlayerData.TrapData.new(Trap.Type.GAS, 3, 3)
	]
	add_child(player)
	generate_trap(Trap.Type.FORCE_PANEL, Vector3(-1, 0, 0), Vector3i(5,0,2))
	generate_trap(Trap.Type.FORCE_PANEL, Vector3(0, 0, -1), Vector3i(-3,0,2))
	generate_trap(Trap.Type.MINE, Vector3(0, 0, 0), Vector3i(-3,0,-4))
	generate_trap(Trap.Type.BOMB, Vector3(0, 0, 0), Vector3i(-2,0,-4))
	generate_trap(Trap.Type.BOMB, Vector3(0, 0, 0), Vector3i(-4,0,-4))
	player.setup(traps)

func is_square_detected(crd) -> bool:
	return marker_layer.get_cell_item(crd + Vector3i(0,-1,0)) != GridMap.INVALID_CELL_ITEM

func detect_square(crd : Vector3i, mark : bool) -> bool:
	var cell = floor_layer.get_cell_item(crd)
	if cell == GridMap.INVALID_CELL_ITEM:
		return false
	
	marker_layer.set_cell_item(crd, 0 if mark else GridMap.INVALID_CELL_ITEM)
	if mark:
		var trap_crd = crd + Vector3i(0,1,0)
		if traps.has(trap_crd):
			var trap : Trap = traps[trap_crd]
			if trap.trap_owner != Multiplayer.id:
				trap.reveal()
	return true

func add_trap(trap : Trap, crd : Vector3i) -> void:
	trap.square = crd
	traps[crd] = trap
	trap.global_position = Vector3(crd) + Vector3(.5, 0, .5)
	add_child(trap)

func add_projectile(shot : Projectile) -> void:
	add_child(shot)
	
func remove_trap_square(crd : Vector3i) -> void:
	traps.erase(crd)

func get_square_trap(crd : Vector3i) -> Trap:
	if traps.has(crd):
		return traps[crd]
	else:
		return null



func is_valid_trap_square(crd : Vector3i) -> bool:
	if floor_layer.get_cell_item(crd + Vector3i(0,-1,0)) == GridMap.INVALID_CELL_ITEM:
		return false
	if traps.has(crd):
		return false
	return true

func add_vfx(vfx, crd : Vector3i) -> void:
	vfx.global_position = Vector3(crd) #+ Vector3(0.5, 0, 0.5)
	add_child(vfx)
	
func activate_trap(crd : Vector3i) -> void:
	var trap = traps[crd]
	#if trap:
		

func generate_trap(type : Trap.Type, dir : Vector3, square : Vector3i):
	var trap = trap_template.instantiate()
	trap.setup(type, dir, -1)
	add_trap(trap, square)

func disarm_trap(crd : Vector3i) -> void:
	var trap = traps[crd]
	trap.disarm()
	traps.erase(crd)
