extends Node3D

class_name Game

const HIGHLIGHT = preload("uid://d3ognkvbqsh4u")
var selected_piece : Piece

const MOVEMENT_HIGHLIGHTER = preload("uid://cnbgugaxpa3g5")
const ATTACK_HIGHLIGHTER = preload("uid://c772javfi1vol")

var possible_positions : Array[Vector2i] = []
# Called when the node enters the scene tree for the first time.

func _ready() -> void:
	#$SuperPawn2.move_to(Vector2(8,8))
	#$SuperPawn.move_to(Vector2(0,0))
	for tile in get_node("Board").get_children():
		tile.is_clicked.connect(movement)
	pass # Replace with function body.
	
func movement(coord:Vector2i):
	if selected_piece:
		if coord in possible_positions:
			selected_piece.move_to(coord)
		deselect()
		
	else:
		select_piece(coord)
		
func get_piece_at(coord) -> Piece:
	for piece in get_node("Pieces").get_children():
		var piece_coord = Vector2i(piece.position.x / 2, piece.position.z / 2)
		if piece_coord == coord:
			return piece
	return null

func select_piece(coord:Vector2i):
	var pos = Vector3(coord.x, 0, coord.y)
	for child in $Pieces.get_children():
		if child.is_in_group("Pieces"):
			if child.position / 2 == pos:
				var piece : Piece = child
				selected_piece = piece
				piece.mesh_instance_3d.material_overlay = HIGHLIGHT
				piece.possible_movements = []
				for scr in piece.piece_res.rules:
					scr.select(piece,self)
				#piece.piece_res.moverules.selectRule(piece, self)
				
				for move in piece.possible_movements:
					var highlighter : Node3D
					var possible_pos = Vector2i(piece.position.x / 2 + move.x, piece.position.z / 2 + move.y)
					var other_piece = get_piece_at(possible_pos)
					if possible_pos not in get_node("Board").all_tiles:
						continue
					if other_piece and other_piece.is_in_group("Enemy"):
						highlighter = ATTACK_HIGHLIGHTER.instantiate()
					else:
						highlighter = MOVEMENT_HIGHLIGHTER.instantiate()
					highlighter.position.x = possible_pos.x * 2
					highlighter.position.z = possible_pos.y * 2
					possible_positions.append(possible_pos)
					add_child(highlighter)
				break
			else:
				deselect()
	pass
	
func deselect():
	if selected_piece:
		selected_piece.mesh_instance_3d.material_overlay = null
	selected_piece = null
	possible_positions = []
	for child in get_children():
		if child.is_in_group("Highlighter"):
			child.queue_free()

func _process(delta: float) -> void:
	pass
