extends Area2D

class_name Satellite

@onready var panels := $Panels
@onready var available_panels : Array = []
@onready var timer := $Timer

var clean := false
var speed := 5.0
var direction := Vector2(1,0)
var cleaners : Array[Astronaut] = []

var wait_time := 1.0
var active := false

### 	 ACCESSORS 	 ###






### 	 BUILT-IN 	 ###

func _ready() -> void:
	connect_signals()
	init_panels()


func _physics_process(delta: float) -> void:
	if active:
		var dist = delta * direction * speed
		for astro in cleaners:
			if !astro.go_clean:
				astro.global_position += dist
		self.global_position += dist


### 	 VIRTUAL 	 ###





### 	 LOGIC 	 ###

func connect_signals() -> void:
	body_entered.connect(_on_body_entered)
	body_exited.connect(_on_body_exited)
	timer.connect("timeout", _on_timer_timeout)
	timer.start(wait_time)
	for panel in available_panels:
		panel.satellite = self
		panel.connect("cleaned", _on_panel_cleaned)


func dispatch_to_panels(astro : Astronaut) -> void:
	var chosen_panel = available_panels.pick_random()
	available_panels.erase(chosen_panel)
	astro.panel = chosen_panel
	astro.set_target(Vector2.ZERO, true)


func check_clean() -> void:
	clean = true
	for panel in panels.get_children():
		if !panel.clean:
			clean = false
	if clean:
		EVENTS.satellite_clean.emit()


func init_panels() -> void:
	for panel in panels.get_children():
		panel.dirt_level = randi_range(GLOBALS.dirt_range.x, GLOBALS.dirt_range.y)
		panel.init_dirt()
		if !panel.clean:
			panel.satellite = self
			available_panels.append(panel)
	if available_panels.is_empty():
		available_panels.append(panels.get_child(0))
		available_panels.back().satellite = self
		available_panels.back().dirt_level = GLOBALS.dirt_range.y
		available_panels.back().init_dirt()
	
	

### 	 SIGNAL-RESPONSE 	 ###

func _on_body_entered(body) -> void:
	if body.get_state_name() != "Clean" and !body.go_clean:
		if !clean and !available_panels.is_empty():
			if cleaners.find(body) == -1:
				cleaners.append(body)
			body.satellite = self
			dispatch_to_panels(body)
		else:
			cleaners.erase(body)
			body.satellite = null
			body.set_state("Idle")


func _on_body_exited(body) -> void:
	pass


func _on_panel_cleaned() -> void:
	pass


func _on_timer_timeout() -> void:
	active = true
