extends CharacterBody3D


const SPEED = 5.0
const JUMP_VELOCITY = 4.5
const SHOVE_POWER = 9

@onready var right_target: Node3D = $RightTarget
@onready var left_target: Node3D = $LeftTarget
@onready var right_cast: RayCast3D = $RightCast
@onready var left_cast: RayCast3D = $LeftCast

enum FaceDirection{LEFT, RIGHT}
var facing:FaceDirection = FaceDirection.RIGHT

var pushTarget:RigidBody3D

func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta

	# Handle jump.
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	var direction := (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		if direction.x>0:
			facing = FaceDirection.RIGHT
		if direction.x<0:
			facing = FaceDirection.LEFT
		#velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		#velocity.z = move_toward(velocity.z, 0, SPEED)
	if Input.is_action_just_pressed("shoot"):
		match facing:
			FaceDirection.RIGHT:
				%SceneManager.makeBullet(right_target.global_position, 19)
			FaceDirection.LEFT:
				%SceneManager.makeBullet(left_target.global_position, -4)
	if Input.is_action_just_pressed("shove"):
		print("try to shove")
		if pushTarget != null:
			print("shove a crate")
			var angle
			if facing==FaceDirection.LEFT:
				angle = -1
			else:
				angle = 1
			pushTarget.apply_central_impulse(Vector3(angle,0,0) * SHOVE_POWER)
	move_and_slide()
	
	for i in get_slide_collision_count():
		var collision = get_slide_collision(i)
		if collision.get_collider() is RigidBody3D:
			collision.get_collider().apply_central_impulse(-collision.get_normal() * 2)
	
	match facing:
		FaceDirection.LEFT:
			if left_cast.is_colliding():
				var collider = left_cast.get_collider()
				if collider is Crate:
					pushTarget = collider
			else:
				pushTarget = null
		FaceDirection.RIGHT:
			if right_cast.is_colliding():
				var collider = right_cast.get_collider()
				if collider is Crate:
					pushTarget = collider
			else:
				pushTarget = null
	
