-- lx-bundle:true

-- 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.

--- Optional font preview registration
-- @module plugins.fontpreview

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

local PAGE_SCROLL_RATIO = 0.85

--- Move the active font preview by one visible page
-- @param direction number negative moves up and positive moves down
-- @return boolean handled
local function scroll_page(direction)
	local view = core.active_view
	local delta = math.max(view:get_line_height(), math.floor(view.size.y * PAGE_SCROLL_RATIO))
	view:scroll_by(0, direction * delta)

	return true
end

--- Create a font preview while keeping its renderer unloaded until needed
-- @param request table shared open request
-- @return table view rendered font view
local function create_preview(request)
	local FontPreview = require("plugins.fontpreview.view")

	return FontPreview(request.doc, request.options)
end

-- One renderer handles both font formats without making either format import this plugin
open_handler.register({
	name = "font",
	formats = { "otf", "ttf" },
	modes = { "preview" },
	create_view = create_preview,
})

command.register({
	-- Move one visible page upward
	["font-preview:page-up"] = {
		requires = { "font_preview" },
		perform = function()
			return scroll_page(-1)
		end,
	},
	-- Move one visible page downward
	["font-preview:page-down"] = {
		requires = { "font_preview" },
		perform = function()
			return scroll_page(1)
		end,
	},
})

-- Font previews offer direct aliases while preserving every shared Ctrl binding
keymap.bind("plugin", {
	font_preview = {
		["lclick"] = "doc:mouse-pan",
		-- Space follows the usual document-reading page controls
		["shift+space"] = "font-preview:page-up",
		["space"] = "font-preview:page-down",
		["pageup"] = "font-preview:page-up",
		["pagedown"] = "font-preview:page-down",
		["+"] = "zoom:in",
		["-"] = "zoom:out",
		["0"] = "zoom:reset",
		["keypad +"] = "zoom:in",
		["keypad -"] = "zoom:out",
		["keypad *"] = "zoom:reset",
		["wheelup"] = "zoom:in",
		["wheeldown"] = "zoom:out",
		["ctrl+wheelup"] = "zoom:in",
		["ctrl+wheeldown"] = "zoom:out",
	},
})
