local export = {}

local m_sortkey = require("Module:Hani-sortkey")
local m_sortkey_sandbox = require("Module:Hani-sortkey/sandbox")

local lang = require("Module:languages").getByCode("zh")
local sc = require("Module:scripts").getByCode("Hani")

local function tag(text)
	return require("Module:script utilities").tag_text(text, lang, sc)
end

local function link(text)
	return require("Module:links").full_link{ term = text, lang = lang, sc = sc, tr = "-" }
end

local a = {}
a[1] = '命裡有時終須有,命裡無時莫強求' -- punctuation
a[2] = 'gas爐' -- non-cjk
a[3] = 'γ粒子' -- non-cjk
a[4] = 'PS/2接口' -- non-cjk + symbols
a[5] = '濕𣲷𣲷' -- exotic unicode
a[6] = '得個……字' -- punctuation?
a[7] = '赛车' -- simplified

function export.showSorting(frame)
	local terms = {}
	
	if frame.args[1] then
		for i, term in ipairs(frame.args) do
			table.insert(terms, mw.text.trim(term))
		end
	else
		terms = a
	end
	
	local module = frame.args.sandbox and m_sortkey_sandbox or m_sortkey
	
	local function comp(term1, term2)
		return (module.makeSortKey(term1)) < (module.makeSortKey(term2))
	end
	
	table.sort(terms, comp)
	
	for i, term in pairs(terms) do
		local title = mw.title.new(term)
		local exists = title and title.exists
		terms[i] = "\n* " .. ( exists and link(term) or tag(term) ) .. " (<code>" .. (module.makeSortKey(term)) .. "</code>)"
	end
	
	return table.concat(terms)
end

function export.showDataModules(frame)
	local chars = {}
	local codepoints = {}
	local modules = {}
	for char in mw.ustring.gmatch(frame.args[1], ".") do
		table.insert(chars, char)
		table.insert(codepoints, mw.ustring.codepoint(char))
		table.insert(modules, m_sortkey.getData(char, true) or "")
	end
	
	local out = {}
	for i, char in ipairs(chars) do
		local exists = mw.title.new(char).exists
		table.insert(out, "\n* " .. ( exists and link(char) or tag(char) ) .. " (" .. codepoints[i] .. " in [[" .. modules[i] .. "]])")
	end
	
	return table.concat(out)
end

function export.sortkey(frame)
	return (m_sortkey.makeSortKey(frame.args[1], frame.args[2], frame.args[3]))
end

function export.showIDSLinks(frame)
	local out = {}
	for IDS, sortkey in pairs(mw.loadData("Module:Hani-sortkey/data/unsupported")) do
		table.insert(out, "\n* " .. link(IDS) .. " → <code>" .. sortkey .. "</code>")
	end
	
	return table.concat(out)
end

return export