extends Node

var daemon_settings_filepath: String = \
		OS.get_data_dir() + "/lbry/lbrynet/daemon_settings.yml"
var settings_cached: bool = false
var cached_settings: Dictionary = {}


func _ready() -> void:
	# If new path for `daemon_settings_filepath` is given on cmdline set it to
	# that
	pass


func get_settings() -> Dictionary:
	"""
	Returns:
		The lbrynet daemon settings parsed from the daemon_settings.yml file, 
		in the form {key: value, ...} where both `key` and `value` are strings.
		The first call of this function will cache the result and subsequest
		calls will return the cached result
	"""
	if settings_cached:
		return cached_settings
	else:
		var settings: Dictionary = {}
		var file := File.new()
		var err: int = file.open(daemon_settings_filepath, File.READ)
		if err == OK:
			var line: String = file.get_line()
			while line:
				var split_line: PoolStringArray = line.split(":", true, 1)
				settings[split_line[0]] = split_line[1].strip_edges()
				line = file.get_line()
		else:
			push_error("Failed to open '%s': %d" % [daemon_settings_filepath, err])
		cached_settings = settings
		settings_cached = true
		return settings


func get_rpc_address() -> PoolStringArray:
	"""
	Returns:
		The address and port of the RPC interface if given in the settings
		file, otherwise empty
	"""
	var settings: Dictionary = get_settings()
	if settings.has("api"):
		var address: PoolStringArray = settings["api"].rsplit(":", true, 1)
		# Replace "localhost" because the `HTTPRequest` node does not resolve
		# that its self
		if address[0] == "localhost":
			address[0] = "127.0.0.1"
		return address
	return PoolStringArray()
