# Hurry Curry! - a game about cooking
# Copyright (C) 2025 Hurry Curry! contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
class_name PathSetting
extends TextSetting

var select_file_icon: Texture2D = preload("res://gui/resources/icons/select_file.svg")
var select_dir_icon: Texture2D = preload("res://gui/resources/icons/select_directory.svg")

var access: FileDialog.Access
var file_mode: FileDialog.FileMode

func _init(new_id: String,
	new_default: String,
	new_file_mode: FileDialog.FileMode,
	new_placeholder: String = "",
	new_access: FileDialog.Access = FileDialog.Access.ACCESS_FILESYSTEM
):
	super(new_id, new_default)
	placeholder = new_placeholder
	access = new_access
	file_mode = new_file_mode

func create_row():
	var row = super ()
	var input: LineEdit = row.value_node;
	input.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	row.value_node = HBoxContainer.new()
	row.value_node.add_child(input)
	var button := Button.new()
	button.icon = select_file_icon if file_mode == FileDialog.FileMode.FILE_MODE_OPEN_FILE else select_dir_icon
	row.value_node.add_child(button)
	button.pressed.connect(func():
		var d := FileDialog.new()
		Global.focused_menu.add_child(d)
		d.move_to_center()
		d.use_native_dialog = true
		d.borderless = true
		d.dir_selected.connect(_selected.bind(input))
		d.file_selected.connect(_selected.bind(input))
		d.file_mode = file_mode
		d.access = access
		d.show()
		# this feels wrong
		d.canceled.connect(d.queue_free)
		d.confirmed.connect(d.queue_free)
	)
	return row

func _selected(path: String, input: LineEdit):
	input.text = path
	input.text_changed.emit(path)
