extends ScrollContainer

signal horizontal_scroll_ended
signal vertical_scroll_ended

var _h_scrollbar_pressed: bool = false
var _v_scrollbar_pressed: bool = false


func _ready() -> void:
	# Signal `scroll_ended` doesn't work, so implement it with `gui_input`
	# See: https://github.com/godotengine/godot/issues/22936
	get_h_scrollbar().connect("gui_input", self, "_on_h_scrollbar_gui_input")
	get_v_scrollbar().connect("gui_input", self, "_on_v_scrollbar_gui_input")


func is_h_scrollbar_at_end() -> bool:
	var distance_to_end: float = (
			get_h_scrollbar().get_max() 
			- get_h_scrollbar().get_page() 
			- get_h_scrollbar().get_value())
	return distance_to_end < 0.001


func is_v_scrollbar_at_end() -> bool:
	var distance_to_end: float = (
			get_v_scrollbar().get_max() 
			- get_v_scrollbar().get_page() 
			- get_v_scrollbar().get_value())
	return distance_to_end < 0.001


func _on_h_scrollbar_gui_input(event: InputEvent) -> void:
	if (
			event is InputEventMouseButton 
			and event.get_button_index() == BUTTON_LEFT
	):
		if event.is_pressed():
			_h_scrollbar_pressed = true
		else:
			if _h_scrollbar_pressed:
				emit_signal("horizontal_scroll_ended")
			_h_scrollbar_pressed = false


func _on_v_scrollbar_gui_input(event: InputEvent) -> void:
	if (
			event is InputEventMouseButton 
			and event.get_button_index() == BUTTON_LEFT
	):
		if event.is_pressed():
			_v_scrollbar_pressed = true
		else:
			if _v_scrollbar_pressed:
				emit_signal("vertical_scroll_ended")
			_v_scrollbar_pressed = false
