extends Area2D

class_name Cursor

@onready var clear_timer := $ClearTimer

var multiselect := false
var dragging := false

var drag_start := Vector2.ZERO


### 	 ACCESSORS 	 ###






### 	 BUILT-IN 	 ###

func _ready() -> void:
	pass


func _physics_process(_delta: float) -> void:
	self.global_position = get_global_mouse_position()


func _input(event: InputEvent) -> void:
	if event.is_action_pressed("multiselect"):
		multiselect = true
	elif event.is_action_released("multiselect"):
		multiselect = false
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if event.is_pressed():
			if event.double_click:
				for astro in GLOBALS.selected:
					astro.unselect()
				GLOBALS.selected.clear()
			else:
				if !GLOBALS.selectables.is_empty():
					if GLOBALS.selected.find(GLOBALS.selectables.back()) != -1:
						GLOBALS.selected.erase(GLOBALS.selectables.back())
						GLOBALS.selectables.back().unselect()
					else:
						if !multiselect:
							for astro in GLOBALS.selected:
								astro.unselect()
							GLOBALS.selected = [GLOBALS.selectables.back()]
						else:
							GLOBALS.selected.append(GLOBALS.selectables.back())
						GLOBALS.selectables.back().select()
							
				elif !GLOBALS.selected.is_empty():
					set_target()
					clear_timer.start()
				else:
					dragging = true	
					drag_start = get_global_mouse_position()
					EVENTS.drag_start.emit(drag_start)
		else:
			if dragging:
				dragging = false
				EVENTS.drag_ended.emit()
	elif event is InputEventMouseMotion:
		update_drag_rectangle()


### 	 VIRTUAL 	 ###





### 	 LOGIC 	 ###

func update_drag_rectangle() -> void:
	EVENTS.drag_update.emit(get_global_mouse_position())


func set_target() -> void:
	for astro in GLOBALS.selected:
		if astro.panel:
			astro.panel.remove_cleaner()
		if astro.satellite:
			astro.satellite.cleaners.erase(astro)
			astro.satellite = null
		astro.go_clean = false
		astro.set_target(get_global_mouse_position())


### 	 SIGNAL-RESPONSE 	 ###


func _on_clear_timer_timeout() -> void:
	GLOBALS.selected.clear()
