extends Node2D

@onready var energy_line: Line2D = %EnergyLine
@onready var ray_cast: RayCast2D = %RayCast

@export_range(1,999,1) var maximum_flow_distance: float = 300
@export var energy: float = 1.0

var energy_distribution_target: CollisionObject2D
var target_accepting_energy: EnergyAcceptor

func _ready() -> void:
	var target_position := Vector2(maximum_flow_distance, 0)
	
	energy_line.add_point(Vector2.ZERO)
	energy_line.add_point(target_position)
	
	ray_cast.target_position = target_position

func _process(delta: float) -> void:
	if ray_cast.is_colliding():
		if not ray_cast.get_collider() == energy_distribution_target:
			if target_accepting_energy: target_accepting_energy.deplete()
			energy_distribution_target = ray_cast.get_collider()
			_find_energy_acceptor(energy_distribution_target)
		energy_line.clear_points()
		energy_line.add_point(Vector2.ZERO)
		energy_line.add_point(Vector2(global_position.distance_to(ray_cast.get_collision_point()), 0))
		if target_accepting_energy:
			target_accepting_energy.energize(energy * delta, ray_cast.get_collision_point())
	elif energy_distribution_target :
		energy_distribution_target = null
		if target_accepting_energy:
			target_accepting_energy.deplete()
			target_accepting_energy = null
		energy_line.clear_points()
		energy_line.add_point(Vector2.ZERO)
		energy_line.add_point(Vector2(maximum_flow_distance, 0))
		
func _find_energy_acceptor(node: Node):
	for child in node.get_children():
		if child is EnergyAcceptor:
			target_accepting_energy = child
			return
	target_accepting_energy = null
