-- lx-bundle:true

--- Shared visible error block for rendered document previews
-- @module core.preview.error_block

local error_block = {}

--- Add one wrapped error message through the receiving preview's row layout
-- @param view table preview receiving the error rows
-- @param message string visible error text
-- @param width number available document width
-- @param options table spacing around the error text
function error_block.add(view, message, width, options)
	options = options or {}
	local padding_x = options.padding_horizontal or 0
	local padding_y = options.padding_vertical or 0
	local wrapped = view:wrap_inline_runs(
		{ { text = message, options = {} } },
		nil,
		math.max(1, width - padding_x * 2)
	)

	for wrapped_index = 1, #wrapped do
		view:add_layout_row(
			wrapped[wrapped_index],
			wrapped_index == 1 and (options.gap_before or 0) or 0,
			{
				x_offset = padding_x,
				content_padding_top = wrapped_index == 1 and padding_y or 0,
				content_padding_bottom = wrapped_index == #wrapped and padding_y or 0,
				error_block = true,
			}
		)
	end
end

--- Draw one error row's shared full-width background
-- @param row table measured preview row
-- @param x number document left edge
-- @param y number row top edge
-- @param width number document width
-- @param design table preview design color provider
function error_block.draw_background(row, x, y, width, design)
	if not row.error_block then
		return
	end

	renderer.draw_rect(
		x,
		math.floor(y),
		width,
		math.ceil(row.height),
		design.get_error_block_background_color()
	)
end

--- Return an error row's text color when the shared block owns it
-- @param row table measured preview row
-- @param design table preview design color provider
-- @return table|nil color error text color
function error_block.get_text_color(row, design)
	return row.error_block and design.get_error_block_text_color() or nil
end

return error_block
