local M = {}
local m_zh = require("Module:zh")
local m_zh_link = require("Module:zh/link")

local function format_Chinese_text(text) return '<span class="Hani" lang="zh">' .. text .. '</span>' end
local function format_rom(text) return text and '<i><span class="tr Latn">' .. text .. '</span></i>' or nil end
local function format_gloss(text) return text and '“' .. text .. '”' or nil end

local function replace_chars(s, tab)
	-- use UTF-8 character pattern for speed
	return s:gsub("[%z\1-\127\194-\244][\128-\191]*", tab)
end

function M.mention(frame)
	return m_zh_link.link(frame, true)
end

function M.der(frame)
	local params = {
		[1] = { list = true },
		["fold"] = { type = "boolean" },
		["name"] = {},
		["title"] = {},
		["hide_pron"] = { type = "boolean" },
	}
	
	local args = require("Module:parameters").process(frame:getParent().args, params)
	local curr_title = mw.title.getCurrentTitle()
	local pagename = curr_title.text
	
	if curr_title.namespace == 0 and pagename ~= "不" then
		error("This template has been deprecated. Please use [[Template:col3]] instead.")
	end
	
	local result = {}
	
	local fold = args["fold"]
	local name = args["name"] or "Derived terms from"
	local saurus = (curr_title.nsText == "Thesaurus")
	local title = args["title"] and " (<i>" .. args["title"] .. "</i>)" or ""
	local no_transcript = args["hide_pron"]
	
	if args["hide_pron"] then
		local m_ts_data = mw.loadData("Module:zh/data/ts")
		for _, word in ipairs(args[1]) do
			if word then
				local formatted_word = {}
				if word:match("/") then
					for w in mw.text.gsplit(word, "/") do
						table.insert(formatted_word, format_Chinese_text("[[" .. w .. "#Chinese|" .. w .. "]]"))
					end
				else
					table.insert(formatted_word, format_Chinese_text("[[" .. word .. "#Chinese|" .. word .. "]]"))
					local word_s = replace_chars(word, m_ts_data)
					if word_s ~= word then
						table.insert(formatted_word, format_Chinese_text("[[" .. word_s .. "#Chinese|" .. word_s .. "]]"))
					end
				end
				table.insert(result, table.concat(formatted_word, "/"))
			end
		end
	else
		for _, word in ipairs(args[1]) do
			note, word = word:match(";(.+)") or nil, word:match("^[^;]+")
			if word then
				local colon_pos = word:find(":")
				local split_word = colon_pos and {word:sub(1, colon_pos - 1), word:sub(colon_pos + 1)}
					or {word}
				local slash_pos = split_word[1]:find("/")
				local split_word_main = slash_pos and split_word[1]:sub(1, slash_pos - 1) or split_word[1]
				if split_word_main ~= pagename then  -- synonyms should not be the same as the title
					table.insert(result,
						m_zh_link.link(frame, nil, split_word, pagename, no_transcript) ..
						(note and " (''" .. note .. "'')" or ""))
				end
			end
		end
	end
	
	return 
		require("Module:columns/old").create_table(
			(mw.ustring.len(pagename) > 1 and 2 or 3), -- column number
			result, -- terms
			true, -- alphabetize
			"#F5F5FF", -- background
			(((#result > 72 or fold) and not saurus) and true or false), -- whether to collapse
			"derivedterms", -- class applied to table containing terms
			name .. " " .. format_Chinese_text(pagename) .. title, -- title
			nil, -- column width
			nil, -- line start (??)
			nil -- lang: not needed
		)
end

local lang_abbrev = {
	['m'] = 'Mandarin',
	['c'] = 'Cantonese', ['g'] = 'Gan', ['h'] = 'Hakka', ['j'] = 'Jin',
	['mb'] = 'Northern Min', ['md'] = 'Eastern Min', ['mn'] = 'Hokkien', ['mn-t'] = 'Teochew',
	['w'] = 'Wu', ['x'] = 'Xiang',
}

function M.cls(frame)
	local args = frame:getParent().args
	local result, categories = {}, {}
	local m_zh_cat = require("Module:zh-cat")
	local space = '<span style="padding-left:4px; padding-right:4px">&nbsp;</span>'
	for _, combination in ipairs(args) do
		local part = mw.text.split(combination, ":")
		local note
		if #part == 2 then
			local dialect = { "" }
			local function annotate(main_text, annotation)
				return "<span style=\"border-bottom: 1px dotted #000; cursor:help\" " ..
					"title=\"" .. annotation .. "\"><i>" .. main_text .. "</i></span>"
			end
			for variety in mw.text.gsplit(part[1], ",") do
				table.insert(dialect, annotate(variety, lang_abbrev[variety]))
			end
			note = table.concat(dialect, " ")
		else
			note = false
			require('Module:debug/track')("zh-mw-no-dialect")
		end
		table.insert(result, m_zh_link.link(frame, nil, { part[2] or part[1], tr = "-" }, pagename) .. -- pagename is undefined!
			(note or ""))
		table.insert(categories, m_zh_cat.categorize("Classifier:" .. (part[2] or part[1])))
	end
	return "<span style=\"padding-left:15px; font-size:80%\"><span style=\"background:#EDFFFF\">(''Classifier'': " ..
		table.concat(result, ";" .. space) .. ")</span></span>" .. 
		(mw.title.getCurrentTitle().nsText == "" and table.concat(categories) or "")
end

function M.wikipedia(frame)
	local args = frame:getParent().args
	local title = mw.title.getCurrentTitle().text
	local wp_data = {
		["zh"] = { "Written Standard Chinese<sup>[[w:Written vernacular Chinese|?]]</sup>", "zh" },
		["cdo"] = { "Eastern Min", "cdo" },
		["gan"] = { "Gan", "zh" },
		["hak"] = { "Hakka", "hak" },
		["lzh"] = { "Classical", "zh" },
		["nan"] = { "Southern Min", "nan" },
		["wuu"] = { "Wu", "zh" },
		["yue"] = { "Cantonese", "zh" },
		["en"] = { "English", "en" },
	}
	
	args = args[1] and args or { "zh" }
	local result = { '<div class="sister-wikipedia sister-project noprint floatright" style="border: 1px solid #aaa; font-size: 90%; background: #f9f9f9; width: 250px; padding: 4px; text-align: left;"><div style="float: left;">[[File:Wikipedia-logo.png|32px|none|link=|alt=]]</div><div style="margin-left: 40px;">[[Wikipedia]] has ' ..
		(args[2] and "articles" or "an article") .. ' on:<ul>' }

	for _, arg in ipairs(args) do
		local lang, pagename = arg:match("(.+):(.+)")
		if not pagename then lang, pagename = arg, title end
		if lang == "zh-classical" then error("Please use lzh instead of zh-classical.")
		elseif lang == "zh-yue" then error("Please use yue instead of zh-yue.")
		elseif lang == "zh-min-nan" then error("Please use nan instead of zh-min-nan.") end
		local lang_data = wp_data[lang] or error("" .. lang .. " is not a recognized language.")
		local annotation = lang_data[1] or false
		if lang == "zh" and not args[2] then
			annotation = false
		elseif annotation then
			annotation = " <span style=\"font-size:80%\">(" .. annotation .. ")</span>"
		end
		local script = require("Module:languages").getByCode("zh"):findBestScript(pagename):getCode()
		table.insert(result, '<li><b class="' .. script .. '" lang="' .. lang_data[2] .. '">[[w&#x3a;' .. lang .. '&#x3a;' .. pagename .. '|' .. pagename .. ']]</b>' .. (annotation or "") .. '</li>')
	end
	
	table.insert(result, '</ul></div></div>')
	
	return table.concat(result)
end

function M.syn_saurus(frame, kind)
	local args = frame:getParent().args
	local title = mw.title.getCurrentTitle().text
	local word = args[1] or title
	local content = mw.title.new("Thesaurus:" .. word):getContent()
	local temp = kind or "syn"
	local template = content:match("{{zh%-" .. temp .. "%-list|([^}]+)}}")
	if template and template ~= "" then
		local set = {}
		for item in mw.text.gsplit(template, "|") do
			table.insert(set, item ~= title and item or nil)
		end
		set["name"] = ((args["name"] or kind) == "ant") and "Antonyms of" or "Synonyms of"
		set["title"] = args["title"] or nil
		if args["fold"] or #set > 10 then set["fold"] = 1 end
		return '<div style="float: right; clear: right; font-size:60%"><span class="plainlinks">[' ..
		tostring(mw.uri.fullUrl("Thesaurus:" .. word, { ["action"] = "edit" })) ..
		' edit]</span></div>' .. frame:expandTemplate{ title = "Template:zh-der", args = set }
	else
		return ""
	end
end

function M.ant_saurus(frame)
	return M.syn_saurus(frame, "ant")
end

function M.div(frame)
	local args = frame:getParent().args
	local m_links = require("Module:links")
	local lang = require("Module:languages").getByCode("zh")
	local pagename = mw.title.getCurrentTitle().text
	local i, result = 1, ""
	
	local function add_link(pagename, description)
		local target_page = mw.title.new(pagename .. description)
		if target_page.exists and not target_page.isRedirect then
			return format_Chinese_text(m_links.language_link{ term = pagename .. description, alt = "~" .. description, lang = lang })
		else
			return format_Chinese_text("~" .. m_links.language_link{ term = description, lang = lang })
		end
	end

	while args[i] do
		if i ~= 1 then result = result .. "''separator ''" end
		result = result .. add_link(pagename, args[i])
		if i == 1 and args["f"] then
			local j = 2
			result = result .. "'', formerly ''" .. add_link(pagename, args["f"])
			while args["f" .. j] do
				result = result .. "'', ''" .. add_link(pagename, args["f" .. j])
				j = j + 1
			end
		end
		i = i + 1
	end
	result = result:gsub("separator", result:match("formerly") and ";" or ",")
	
	return format_Chinese_text("(") .. result .. format_Chinese_text(")")
end

function M.short(frame)
	local args = frame:getParent().args
	local pinyin = args["tr"] or false
	local gloss = args["t"] or false
	local nocap = args["nocap"] or false
	local notext = args["notext"] or false
	local comb = args["and"] or false
	local nodot = args["nodot"] or false
	local ital = frame.args["ital"] or false
	local noterm = not args[1] or false
	local t, s, tr, anno, word = {}, {}, {}, {}, {}
	local start = (ital and "<i>" or "") .. (nocap and "s" or "S") .. "hort for " .. (ital and "</i>" or "")
	local cat = require("Module:zh-cat").categorize("short")
	if comb then
		for _, arg in ipairs(args) do
			table.insert(word, m_zh_link.link(frame, nil, { arg }))
		end
		return start .. table.concat(word, " + ") .. 
			(gloss and ": " .. format_gloss(gloss) or "") ..
			((ital and not nodot) and "<i>.</i>" or "") .. cat
	end
	for _, arg in ipairs(args) do
		cap = arg:find("^%^")
		arg = arg:gsub("^%^", "")
		table.insert(t, "[[" .. arg .. "]]")
		table.insert(s, "[[" .. m_zh.ts(arg) .. "]]")
		if not pinyin then
			local extracted_pron, _ = require("Module:zh/extract").extract_pron(arg, "m", cap)
			table.insert(tr, extracted_pron)
		end
	end
	local trad = format_Chinese_text(table.concat(t))
	local simp = format_Chinese_text(table.concat(s))
	pinyin = pinyin ~= "-" and pinyin or (#tr == #t and table.concat(tr, " ") or false)
	table.insert(anno, format_rom(pinyin))
	table.insert(anno, format_gloss(gloss))
	return (notext and "" or start) .. (noterm and "" or trad .. (trad ~= simp and "/" .. simp or "") .. 
		((pinyin or gloss) and " (" .. table.concat(anno, ", ") .. ")" or "") .. 
		((ital and not nodot) and "<i>.</i>" or "")) .. cat
end

return M
"https://si.wiktionary.org/w/index.php?title=Module:zh/templates&oldid=82090" වෙතින් සම්ප්‍රවේශනය කෙරිණි