-- lx-bundle:true

--- Register line layout commands without loading their text processing
-- @module plugins.alignblock

local command = require("core.command")
local keymap = require("core.keymap")

local main

--- Load line layout processing on its first command
-- @return table implementation
local function get_main()
	if not main then
		main = require("plugins.alignblock.main")
	end

	return main
end

--- Build one lazy line layout command
-- @param operation_name string wrap or split
-- @param width_mode string default or cursor
-- @param whole_document boolean whether to ignore the selection
-- @return table command_definition
local function lazy_line_command(operation_name, width_mode, whole_document)
	return {
		requires = { "doc", "edit" },
		perform = function()
			return get_main().run(operation_name, width_mode, whole_document)
		end,
	}
end

--- Build one lazy command backed by a named implementation function
-- @param operation_name string exported operation name
-- @return table command_definition
local function lazy_command(operation_name)
	return {
		requires = { "doc", "edit" },
		perform = function()
			return get_main()[operation_name]()
		end,
	}
end

command.register({
	["lines:wrap"] = lazy_line_command("wrap", "default", false),
	["lines:wrap-at-cursor"] = lazy_line_command("wrap", "cursor", false),
	["lines:wrap-all"] = lazy_line_command("wrap", "default", true),
	["lines:split"] = lazy_line_command("split", "default", false),
	["lines:split-at-cursor"] = lazy_line_command("split", "cursor", false),
	["lines:split-all"] = lazy_line_command("split", "default", true),
	["lines:merge"] = lazy_command("merge"),
	["lines:merge-blocks"] = lazy_command("merge_blocks"),
	["lines:merge-all"] = lazy_command("merge_all"),
	["lines:normalize-paragraphs"] = lazy_command("normalize_paragraphs"),
})

keymap.bind("plugin", {
	text_editor = {
		-- Keep common line layout actions available before their implementation loads
		["shift+ctrl+w"] = "lines:wrap",
		["shift+ctrl+m"] = "lines:merge",
		["shift+ctrl+alt+enter"] = "lines:wrap-at-cursor",
	},
})
