extends HBoxContainer

signal file_changed(path: String)

@onready var root = get_tree().root
@onready var open_file = $"switch"
@onready var path = $"value"
@onready var upload_file = $"save"

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	print("User data dir located in " + OS.get_data_dir())
	open_file.pressed.connect(func():
		var file_dialog = FileDialog.new()
		file_dialog.use_native_dialog = true
		file_dialog.file_mode = FileDialog.FILE_MODE_OPEN_FILE
		file_dialog.access = FileDialog.ACCESS_FILESYSTEM
		file_dialog.current_path = OS.get_data_dir().path_join("FunkPanion/")
		file_dialog.file_selected.connect(func(path_string: String):
			var localized = path_string.simplify_path().replace(OS.get_data_dir().path_join("FunkPanion/"), "user://")
			path.text = localized
			file_changed.emit(localized)
			file_dialog.queue_free()
		)
		file_dialog.canceled.connect(func(path_string: String):
			root.remove_child(file_dialog)
			file_dialog.queue_free()
		)
		root.add_child(file_dialog)
		file_dialog.popup()
	)
	upload_file.pressed.connect(func():
		if path.text.length() > 0:
			print("path text yes", path.text)
			if FileAccess.file_exists(path.text) and path.text.findn("user://") != 0 and path.text.findn("res://") != 0 and ProjectSettings.localize_path(path.text).findn("user://") != 0:
				print("path exists")
				if not DirAccess.dir_exists_absolute("user://uploads/"):
					DirAccess.make_dir_absolute("user://uploads/")
				var new_path = "user://uploads/".path_join(path.text.get_file())
				var dir = DirAccess.open(path.text.get_base_dir())
				dir.copy(path.text.get_file(), new_path)
				path.text = new_path
				file_changed.emit(new_path)
	)