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

--- Basic and full HTML character-reference encoder
-- @module core.lib.html_encode

local encode_map = require("core.lib.html_encode_map")

local MAP
if type(encode_map) == "table" and type(encode_map.ENTITIES) == "table" then
	MAP = encode_map.ENTITIES
elseif type(encode_map) == "table" then
	MAP = encode_map
else
	error("core.lib.html_encode_map returned a non-table value")
end

local BASIC = {
	["&"] = "&amp;",
	["<"] = "&lt;",
	[">"] = "&gt;",
	['"'] = "&quot;",
	["'"] = "&#39;",
}

local html_encode = {}

--- Encode UTF-8 text using the five characters that need ordinary HTML escaping
-- @param text any source value
-- @return string encoded_text
function html_encode.encode_basic(text)
	local src = tostring(text or "")
	return (src:gsub("[&<>\"']", BASIC))
end

--- Encode every character covered by the generated HTML reference map
-- @param text any source value
-- @return string encoded_text
function html_encode.encode_full(text)
	local src = tostring(text or "")
	return (src:gsub("[%z\1-\127\194-\244][\128-\191]*", function(ch)
		return MAP[ch] or BASIC[ch] or ch
	end))
end

return html_encode
