extends Area2D
class_name RisingLevel

@export var RISING_SPEED = 30
const FORCE_CHECK_FREQUENCY = 5

var duration = 0

func _enter_tree():
	g_game_state.restore_checkpoint.connect(on_restore_checkpoint)

func _ready():
	body_entered.connect(_body_entered)
	area_entered.connect(_area_entered)
	body_exited.connect(_body_exited)

func _exit_tree():
	g_game_state.restore_checkpoint.disconnect(on_restore_checkpoint)

func _physics_process(delta):
	$shape.position.y -= RISING_SPEED * delta
	self.position = self.position
	g_game_state.save_level_rising_height($shape.position.y)

	duration += delta
	if duration > FORCE_CHECK_FREQUENCY:
		duration = 0
		for body in get_overlapping_bodies():
			process_body(body, true)


func _body_entered(body):
	process_body(body, false)
func _area_entered(body):
	if body.is_in_group("factory_death"):
		body.get_parent().queue_free()

func _body_exited(body):
	if body.is_in_group("player"):
		body.unswim()

func process_body(body, force= false):
	if force == false && body.is_in_group("player"):
		body.swim()

	if body.is_in_group("npc"):
		body.die(RISING_SPEED)

func on_restore_checkpoint(level):
	$shape.position.y = level
