local M = {}


local function ends_with(str, ending)
	return ending == "" or str:sub(-#ending) == ending
end


local function save_file_from_dependency(dependency_file_path, output_file_path)
	local content = editor.get(dependency_file_path, "text")
	local file, err = io.open(output_file_path, "w")
	if not file then
		print("Error:", err)
		return false
	end
	file:write(content)
	file:close()
	print("Write file at", output_file_path)
	return true
end


function M.get_commands()
	return {
		{
			label = "Assign Layers",
			locations = { "Edit" },
			query = { selection = {type = "resource", cardinality = "one"} },
			active = function(opts)
				local path = editor.get(opts.selection, "path")
				return ends_with(path, ".gui")
			end,
			run = function(opts)
				local file = opts.selection
				print("Run script for", editor.get(file, "path"))
				save_file_from_dependency('/druid/editor_scripts/run_python_script_on_gui.sh', "./build/run_python_script_on_gui.sh")
				save_file_from_dependency('/druid/editor_scripts/setup_layers.py', "./build/setup_layers.py")
				return {
					{
						action = "shell",
						command = {
							"bash",
							"./build/run_python_script_on_gui.sh",
							"./build/setup_layers.py",
							"." .. editor.get(file, "path")
						}
					}
				}
			end
		},

		{
			label = "Create Druid Widget",
			locations = { "Edit", "Assets" },
			query = { selection = {type = "resource", cardinality = "one"} },
			active = function(opts)
				local path = editor.get(opts.selection, "path")
				return ends_with(path, ".gui")
			end,
			run = function(opts)
				local file = opts.selection
				print("Run script for", editor.get(file, "path"))
				save_file_from_dependency('/druid/editor_scripts/run_python_script_on_gui.sh', "./build/run_python_script_on_gui.sh")
				save_file_from_dependency('/druid/editor_scripts/create_druid_component.py', "./build/create_druid_component.py")
				save_file_from_dependency('/druid/editor_scripts/widget.lua_template', "./build/widget.lua_template")
				return {
					{
						action = "shell",
						command = {
							"bash",
							"./build/run_python_script_on_gui.sh",
							"./build/create_druid_component.py",
							"." .. editor.get(file, "path")
						}
					}
				}
			end
		}
	}
end


return M
