class_name Slime
extends Enemy

const MIN_JUMP_TIMER := 1.0
const MAX_JUMP_TIMER := 4.0
const JUMP_VEL := 40.0

@onready var anim: AnimationPlayer = $AnimationPlayer
@onready var jump_timer: Timer = $JumpTimer
@onready var slush_timer: Timer = $SlushTimer
@onready var squish: AudioStreamPlayer2D = $Squish
@onready var jump: AudioStreamPlayer2D = $Jump

func _ready():
	super._ready()
	sm.add(_chase_player_start, Callable(), Callable(), _chase_player_fixed_update)
	sm.add(_jump_start,_jump_update)
	sm.add(_idle_enter)
	sm.start(_chase_player_start)
	
	jump_timer.timeout.connect(func(): 
		if !player_alive:
			sm.change(_idle_enter)
			return
		sm.change(_jump_start))
	
	slush_timer.timeout.connect(func():
		if randf() > 0.75 && !squish.playing:
			squish.play()
		)
		
	hit_collider.connect(_on_hit_collider)

func _idle_enter():
	anim.play("idle")
	
func _chase_player_start():
	anim.play("squish")
	jump_timer.start(randf_range(MIN_JUMP_TIMER, MAX_JUMP_TIMER))

var before_jump_y:float
#var jump_timeout:float

func _jump_start():
	before_jump_y = global_position.y
	anim.play("jump")
	velocity = dir_to_player() * speed * 4.5 + Vector2.UP * JUMP_VEL
	play(jump)
	#jump_timeout = 2.0
	
func _jump_update(delta:float):
	velocity -= Vector2.UP * JUMP_VEL * 6 * delta
	if global_position.y >= before_jump_y:
		velocity.y = 0.0
		sm.change(_chase_player_start)
	
func _process(delta: float) -> void:
	super._process(delta)
	if can_fire && is_aim_ok(global_position):
		# see if we are facing the player
		var b:Bolt = fire_bullet(global_position, -transform.y )
		if b:
			b.detector.collision_mask = ~C.LYR_MASK_ENEMY

func _on_hit_collider(collider:CollisionObject2D):
	if collider is Player:
		collider.push(dir_to_player() * 80)
	if sm.current_state_name == "jump":
		sm.change(_chase_player_start)

func attach_bullet(bullet:Node2D):
	bullet.queue_free()
