@tool
class_name Piece
extends Node3D

@export var piece_res : PieceRes
var is_moving : bool = false
var is_rotating: bool = false
var rotation_target: Vector3
var target : Vector2
var start_pos :Vector3
var start_coord: Vector2i
var mesh_instance_3d: MeshInstance3D
var possible_movements: Array[Vector2i]
@export var team: String = "us"


const PIECE_WHITE = preload("uid://brrbuo0i0e5bh")
const PIECE_RED = preload("uid://bekkxcgjt3hct")
const PIECE_BLACK = preload("uid://bxg7bjgiqfnru")

@onready var attack_area_3d: Area3D = $AttackArea3D
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	for rule in piece_res.rules:
		rule.ready(self)
	print(piece_res.material)
	var mesh_instance = MeshInstance3D.new()
	mesh_instance.mesh = piece_res.mesh
	add_child(mesh_instance)
	mesh_instance_3d = mesh_instance
	if team == "us":
		add_to_group("PlayerPieces")
		mesh_instance_3d.material_override = PIECE_WHITE
	if team == "them":
		print("dadwdawf<sef")
		add_to_group("Enemy")
		mesh_instance_3d.material_override = PIECE_RED
	start_coord = to_coord()


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if is_moving:
		#move to target
		var x_diff = 0
		var z_diff = 0
		
		if target.x < start_pos.x:
			x_diff = -(start_pos.x - target.x)
		else:
			x_diff = (target.x - start_pos.x) 
			
		if target.y < start_pos.z:
			z_diff = -(start_pos.z - target.y)
		else:
			z_diff = (target.y - start_pos.z) 
		
	
		global_translate(Vector3(x_diff, 0, z_diff).normalized() * delta * piece_res.movement_speed)
		if abs(position.x - target.x) < 0.1:
			position.x = target.x
		if abs(target.y - position.z) < 0.1:
			position.z = target.y
		
		if position.z == target.y and position.x == target.x:
			is_moving = false
		pass
	if is_rotating:
		
		if rotation_target == rotation:
			is_moving = true
		pass
	pass

func move_to(new_target: Vector2):
	for moverule_script in piece_res.rules:
		moverule_script.before_move(self)
	#if piece_res.piece_type == PieceRes.PieceType.PAWN:
		#possible_movements = [Vector2i(0,1)]
	target = new_target * 2
	start_pos = position
	
	#var angle = atan2((position.z - target.y),(position.x- target.x))
	#rotation.y = angle
	#rotate_y(angle)
	
	look_at(Vector3(target.x,0,target.y), Vector3.UP)
	is_moving = true
	pass
	
func rotate_to(new_rotation: Vector3):
	is_rotating = true
	rotation_target = new_rotation
	pass

func to_coord() -> Vector2i:
	return Vector2i(position.x / 2., position.z / 2.)

func die():
	queue_free()
	pass

func _on_attack_area_3d_body_entered(body: Node3D) -> void:
	if body == self:
		return
	print("body entered")
	if body.is_moving:
		self.queue_free()
	if is_moving:
		body.queue_free()
	pass # Replace with function body.
