extends Area2D

class_name DragArea

@onready var shape := $CollisionShape2D

var start_pos := Vector2.ZERO
var other_pos := Vector2.ZERO
var diagonal := Vector2.ZERO



### 	 ACCESSORS 	 ###






### 	 BUILT-IN 	 ###

func _ready() -> void:
	connect_signals()




### 	 VIRTUAL 	 ###





### 	 LOGIC 	 ###

func connect_signals() -> void:
	EVENTS.drag_start.connect(_on_drag_started)
	EVENTS.drag_update.connect(_on_drag_updated)
	EVENTS.drag_ended.connect(_on_drag_ended)

func update_size() -> void:
	diagonal = other_pos - start_pos
	self.scale = abs(diagonal)
	self.global_position = start_pos + (diagonal/2.0)


func activate() -> void:
	update_size()
	self.visible = true
	shape.set_deferred("disabled", false)


func deactivate() -> void:
	for astro in GLOBALS.selected:
		astro.unselect()
	GLOBALS.selected.clear()
	for astro in get_overlapping_bodies():
		GLOBALS.selected.append(astro)
		astro.select()
	self.visible = false
	shape.set_deferred("disabled", true)
	

### 	 SIGNAL-RESPONSE 	 ###

func _on_drag_started(initial_pos : Vector2) -> void:
	start_pos = initial_pos
	other_pos = start_pos
	activate()
	


func _on_drag_updated(new_pos : Vector2) -> void:
	other_pos = new_pos
	update_size()


func _on_drag_ended() -> void:
	deactivate()
