local export = {}

local m_zh = require("Module:zh")
local m_data = require("Module:zh-cat/data")

function export.generateClsLink(text, doNotUsePagename)
	local trad = doNotUsePagename and text or mw.title.getCurrentTitle().text
	local simp = m_zh.ts(trad)
	return "Thể loại:Danh từ tiếng Trung Quốc có loại từ " .. (trad ~= simp and (trad .. "/" .. simp) or trad)
end
	
function export.categorize(frame)
	local args = type(frame) == "table" and frame:getParent().args or { frame }
	local PAGENAME = mw.title.getCurrentTitle().text
	local sortkey = require("Module:zh-sortkey").makeSortKey(PAGENAME)
	local text = ""
	for _, cat in ipairs(args) do
		if mw.ustring.match(cat, "Loại từ") then
			local parts = mw.text.split(cat, ":")
			text = text .. "[[" .. export.generateClsLink(parts[2], true) .. "|" .. sortkey .. "]]"
		
		elseif m_data.conventional_names[mw.ustring.lower(cat)] then
			text = text .. "[[Category:" .. m_data.conventional_names[mw.ustring.lower(cat)] .. "|" .. sortkey .. "]]"
		else
			text = text .. "[[Category:zh:" .. cat .. "|" .. sortkey .. "]]"
		end
	end
	return (mw.title.getCurrentTitle().nsText == "" and text or "")
end

function export.clsCat(frame)
	local PAGENAME = mw.title.getCurrentTitle().text
	local part = mw.text.split(PAGENAME, " ")
	local character = part[#part]
	local sortkey = require("Module:zh-sortkey").makeSortKey(character)
	return "Chinese nouns using " .. require("Module:zh/link").link(frame, nil, { character, tr = "-" }, character) ..
		" as their classifier.\n[[Category:Chinese nouns by classifier|" .. sortkey .. "]]"
end

return export