class_name ArrowShooter
extends RayCast2D

@onready var arrow: PackedScene = preload("res://puzzles/arrow/arrow.tscn")
@onready var timer: Timer = $ShootTimer
@onready var shoot_dir: Vector2i = self.target_position.normalized()

@export var arrow_speed: int = 400
@export var shoot_timer: float = 3.0
@export var offset_start_time: float = 0.0
var _default_offset: float = 0.0

var is_stopped = false
var _arrows_shot: Array[Arrow] = []

func _ready():
	_default_offset = offset_start_time

func _process(delta):
	if is_stopped:
		timer.stop()
	
	if offset_start_time > 0:
		offset_start_time -= 1
	elif offset_start_time <= 0 and timer.is_stopped():
		timer.start(shoot_timer)

func _on_shoot_timer_timeout():
	var inst: Arrow = arrow.instantiate()
	inst.shoot(shoot_dir, arrow_speed)
	add_child(inst)
	_arrows_shot.push_back(inst)

func reset():
	for arrow in _arrows_shot:
		if arrow != null:
			arrow.queue_free()
	offset_start_time = _default_offset
	is_stopped = true
