-- @module plugins.window_test

-- This file is part of Lx, created by Liqube <www.liqube.com>
-- Copyright Liqube Audio. All rights reserved.
-- Lx Interim License. See LICENSE for details.

--- Register native window test commands without loading their test UI

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

local main

--- Load the window test UI on its first command
-- @return table implementation
local function get_main()
	if not main then
		main = require("plugins.window_test.main")
	end

	return main
end

--- Read and validate a window ID command argument
-- @param args table|nil command arguments
-- @param command_name string command shown in an error
-- @return number|nil window_id
local function get_window_id(args, command_name)
	local window_id = type(args) == "table" and args.id or nil

	if type(window_id) ~= "number" or window_id <= 0 or window_id % 1 ~= 0 then
		core.error("Use %s(id: <positive window ID>)", command_name)
		return nil
	end

	return window_id
end

--- Close one native test window
-- @param context table command context
-- @param args table command arguments
-- @return boolean closed
local function close_window(context, args)
	local window_id = get_window_id(args, "win:close")

	return window_id and get_main().close(window_id) or false
end

--- Toggle one test window's right pane
-- @param context table command context
-- @param args table command arguments
-- @return boolean toggled
local function toggle_right(context, args)
	local window_id = get_window_id(args, "win:toggle-right")

	return window_id and get_main().toggle_right(window_id) or false
end

--- Redraw one native test window
-- @param context table command context
-- @param args table command arguments
-- @return boolean redrawn
local function redraw(context, args)
	local window_id = get_window_id(args, "win:redraw")

	return window_id and get_main().redraw(window_id) or false
end

command.register({
	-- Keep the manual commands available while their large test UI stays unloaded
	["win:open"] = function()
		return get_main().open()
	end,
	["win:close-last"] = function()
		return get_main().close_last()
	end,
	["win:close"] = close_window,
	["win:list"] = function()
		return get_main().list()
	end,
	["win:toggle-right"] = toggle_right,
	["win:redraw"] = redraw,
})
