extends Node
# https://docs.godotengine.org/en/stable/tutorials/scripting/singletons_autoload.html

signal state_changed(previous, new)

enum State {UNLOADED, LOADED}

const config_path = "user://logue.cfg"

var config = ConfigFile.new()
var db = SQLite.new()
var current_scene = null
var current_state = State.UNLOADED

func _ready():
	var root = get_tree().root
	current_scene = root.get_child(root.get_child_count() - 1)
	
	db.verbosity_level = SQLite.VERBOSE
	
	var err = config.load(config_path)
	if err == OK:
		var db_path = config.get_value("general", "db_path")
		var db_success = load_db(db_path)
		if not db_success:
			# HACK: File picker on Android is broken
			const possible_cfg_paths = ["/foo/bar/logue.cfg"]
			for possible_path in possible_cfg_paths:
				if FileAccess.file_exists(possible_path):
					db_success = load_db(possible_path)
					if db_success:
						break
				

func switch_state(new: State):
	var old = current_state
	if old == new:
		return

	current_state = new
	emit_signal("state_changed", old, new)
	#signal state_changed(old, new)

func load_db(path: String):
	db.path = path
	var success = db.open_db()
	if success:
		config.set_value("general", "db_path", path)
		config.save(config_path)
		switch_state(State.LOADED)
	else:
		db.path = ""
		switch_state(State.UNLOADED)

func goto_scene(path):
	call_deferred("_deferred_goto_scene", path)

func _deferred_goto_scene(path):
	# It is now safe to remove the current scene.
	current_scene.free()

	# Load the new scene.
	var s = ResourceLoader.load(path)

	# Instance the new scene.
	current_scene = s.instantiate()

	# Add it to the active scene, as child of root.
	get_tree().root.add_child(current_scene)

	# Optionally, to make it compatible with the SceneTree.change_scene_to_file() API.
	get_tree().current_scene = current_scene
