extends CharacterBody2D


const SPEED = 200.0
const JUMP_VELOCITY = -450.0
const PUSH_FORCE = 500

var faceLeft = false
var pushRightEnabled = false
var pushLeftEnabled = false
var pushTarget

@onready var right_cast: RayCast2D = $rightCast
@onready var left_cast: RayCast2D = $leftCast
@onready var right_target: Node2D = $rightTarget
@onready var left_target: Node2D = $leftTarget



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 direction := Input.get_axis("left", "right")
	if Input.is_action_just_pressed("shove") && pushRightEnabled && faceLeft == false:
		pushTarget.apply_central_impulse(Vector2(1,0)*PUSH_FORCE)
		pushRightEnabled = false 
	if Input.is_action_just_pressed("shove") && pushLeftEnabled && faceLeft == true:
		print("can actually push")
		pushTarget.apply_central_impulse(Vector2(-1,0)*PUSH_FORCE)
		pushLeftEnabled = false
	# Shoot Attach
	if Input.is_action_just_pressed("shoot"):
		if faceLeft == false:
			%SceneManager.makeBullet(right_target.global_transform, 700)
		if faceLeft == true:
			%SceneManager.makeBullet(left_target.global_transform, -700)
	
	if direction:
		velocity.x = direction * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		
	if direction <0:
		faceLeft = true
	if direction >0:
		faceLeft = false
			

	move_and_slide()
	if right_cast.is_colliding():
		print("something on my right")
		var collider = right_cast.get_collider()
		if collider is Node:
			if collider is RigidBody2D:
				print("shove this crate")
				#record that we can shove right
				pushRightEnabled = true
				#record what object to shove 
				pushTarget = collider
				
	if left_cast.is_colliding():
		print("something on my left")
		var collider =  left_cast.get_collider()
		if collider is Node:
			if collider is RigidBody2D:
				print("shove this crate")
				#record that we can shove left
				pushLeftEnabled = true
				#record what object to shove 
				pushTarget = collider
		
		
		
	for i in get_slide_collision_count():
		var c = get_slide_collision(i)
		if c.get_collider() is RigidBody2D:
			c.get_collider().apply_central_impulse(-c.get_normal() * 50)