extends Enemy

@onready var turret: Sprite2D = $Turret
@onready var turret_base: Sprite2D = $TurretBase
@onready var fire_point: Marker2D = $Turret/FirePoint

func _ready():
	super._ready()
	sm.add(Callable(), _track_player_update)
	sm.start(_track_player_update)
	
func _track_player_update(delta:float):
	var to_plyr := dir_to_player()
	rotate_to(turret, to_plyr, rotate_speed_deg * delta)
	# see if we are facing the player
	var dp:float = to_plyr.dot(-turret.transform.y)
	if dp > 0.98 && can_fire:
		var b:Bolt = fire_bullet(fire_point.global_position, -turret.transform.y )
		if b:
			b.damage = 4
			b.detector.collision_mask = ~C.LYR_MASK_ENEMY

func _physics_process(delta: float) -> void:
	velocity = Vector2.ZERO

func attach_bullet(bullet:Node2D):
	var original_transform:Transform2D = bullet.transform
	if bullet.get_parent():
		bullet.get_parent().remove_child(bullet)
		
	turret.add_child(bullet)
	bullet.global_position = original_transform.origin
	bullet.global_rotation = original_transform.get_rotation()

func _flash_on(spr:Sprite2D, enable:bool) -> bool:
	turret.set_instance_shader_parameter("blink", 1.0 if enable else 0.0)
	turret_base.set_instance_shader_parameter("blink", 1.0 if enable else 0.0)
	return true
	
