local export = {}
local m_links = require("Module:links")
local m_languages = require("Module:languages")
local zh = m_languages.getByCode("zh")

local variety_list = {
	"Classical", "Formal", "Taxonomic", 
	"Mandarin", "Cantonese", "Gan", "Hakka", "Huizhou", "Jin", "Jiuxing Yumin",
	"Min Bei", "Min Dong", "Min Nan", "Puxian Min", "Min Zhong", "Zhongshan Min",
	"Southern Pinghua", "Northern Pinghua", "Shehua", "Waxiang", "Wu", "Xiang"
}

local variety_list_vi = {
	"Cổ điển", "Trang trọng", "Phân loại", 
	"Quan thoại", "Quảng Đông", "Cám", "Khách Gia", "Huy Châu", "Tấn", "Jiuxing Yumin",
	"Mân Bắc", "Mân Đông", "Mân Nam", "Phủ Tiên", "Mân Trung", "Mân Trung Sơn",
	"Nam Bình", "Bắc Bình", "Xa", "Ngõa Hương", "Ngô", "Tương"
}

local variety_colour = {
	["Classical"]		= "FAF0F2",
	["Formal"]			= "FAF0F2",
	["Taxonomic"]		= "FAF0F2",
	["Mandarin"]		= "FAF5F0",
	["Cantonese"]		= "F0F5FA",
	["Gan"]				= "F0FAF3",
	["Hakka"]			= "FAF0F6",
	["Huizhou"]			= "FAF9F0",
	["Jin"]				= "F0F5FA",
	["Jiuxing Yumin"]	= "FAF0FE",
	["Min Bei"]			= "F7FAF0",
	["Min Dong"]		= "F7FAF0",
	["Min Nan"]			= "F7FAF0",
	["Puxian Min"]		= "F7FAF0",
	["Min Zhong"]		= "F7FAF0",
	["Zhongshan Min"]	= "F7FAF0",
	["Southern Pinghua"]= "F0F5FA",
	["Northern Pinghua"]= "F0F5FA",
	["Shehua"]			= "FAF0F6",
	["Waxiang"]			= "F0FAF6",
	["Wu"]				= "F4F0FA",
	["Xiang"]			= "F0F2FA",
}

local special_note = {
	["Classical"] = "[[w:Classical Chinese|Cổ điển Hán văn]]",
	["Formal"] = "Ngôn ngữ viết <small>([[w:Bạch thoại|Bạch thoại]])</small>",
	["Taxonomic"] = "Tên phân loại",
}

function export.main(frame)
	local args = frame:getParent().args
	local pagename = mw.title.getCurrentTitle().text
	local target_page = args[1] or pagename
	local resource_page = "Module:zh/data/dial-syn/" .. target_page
	local variety_data = require("Module:zh/data/dial")
	local m_syndata
	if mw.title.new(resource_page).exists then
		m_syndata = require(resource_page).list
	else
		return frame:expandTemplate{ title = "Template:zh-dial/uncreated", args = { target_page } }
	end
	
	local template = {
		["Classical"]		=	{},
		["Formal"]			=	{},
		["Taxonomic"]		= 	{},
		["Mandarin"]		=	{},
		["Cantonese"]		=	{},
		["Gan"]				=	{},
		["Hakka"]			=	{},
		["Huizhou"]			=	{},
		["Jin"]				= 	{},
		["Jiuxing Yumin"]	= 	{},
		["Min Bei"]			=	{},
		["Min Dong"]		= 	{},
		["Min Nan"]			=	{},
		["Puxian Min"]		=	{},
		["Min Zhong"]		=	{},
		["Zhongshan Min"]	=	{},
		["Southern Pinghua"]=	{},
		["Northern Pinghua"]=	{},
		["Shehua"]			=	{},
		["Waxiang"]			=	{},
		["Wu"]				=	{},
		["Xiang"]			=	{},
	}
	
	--allow alternative title linking for sum-of-parts tables
	local title = m_syndata["title"] or ""
	if title == "" then
		title = target_page
	end
	m_syndata["title"] = nil
	
	local main_title = m_links.full_link( { term = mw.ustring.gsub(title, "[0-9%-]", ""), lang = zh } )
	
	local syn_table = { [=[
	<div class="NavFrame collapsed" style="border:0px; max-width: 40em; text-align:center;"><div class="NavHead" style="font-size:105%; border:1px solid #aaaaaa; margin-left:-1px; background-color:#CCCCFF; text-align:center;" cellpadding="3">Từ địa phương đồng nghĩa với ]=] ..
		main_title .. ' (“' .. m_syndata["meaning"] .. '”) ' ..
		"[[Template:zh-dial-map/" .. target_page .. '|<small>&#91;bản đồ&#93;</small>]]\n' .. [=[</div><div class="NavContent"> 
	{| class="wikitable" style="margin:0; text-align:center; width: 100%"
	|-
	! style="background:#E8ECFA" | Ngôn ngữ
	! style="background:#E8ECFA" | Vùng
	! style="background:#E8ECFA" | Từ]=] .. [=[
	<div style="float: right; clear: right; font-size:60%"><span class="plainlinks">[]=] ..
		tostring(mw.uri.fullUrl("Module:zh/data/dial-syn/" .. target_page, { ["action"] = "edit" })) ..
	' sửa]</span></div>' }
	
	m_syndata["meaning"] = nil
	if m_syndata["note"] then
		note = m_syndata["note"]
		m_syndata["note"] = nil
	end
	if m_syndata["Formal"][1] == "" then
		m_syndata["Formal"] = { target_page }
	elseif m_syndata["Formal"][1] == "-" then
		m_syndata["Formal"] = nil
	end
	
	for location, synonym_set in pairs(m_syndata) do
		if synonym_set[1] ~= "" then
			local formatted_synonyms = {}
			for i, synonym in ipairs(synonym_set) do
				local synonym_note = mw.text.split(synonym, ":")
				local synonym_etym = mw.text.split(synonym_note[1], "_")
				local syn, etym, note = synonym_etym[1], synonym_etym[2], synonym_note[2]
				local synonym_link = m_links.full_link( {
						term = syn .. (etym and string.format("#รากศัพท์ %s", etym) or ""),
						alt = etym and (syn .. string.format("<sub>%s</sub>", etym)),
						lang = zh
					} )
				note = note and ' <span style="font-size:60%"><i>' .. note .. '</i></span>' or ""
				table.insert(formatted_synonyms, synonym_link .. note)
			end
			local location_data = variety_data[location] or error("No data for the location " .. location .. "!")
			local location_name = mw.ustring.gsub(location_data.english or location, "(%(.*%))", "<small>%1</small>")
			local location_link = location_data.link or location_name
			table.insert(template[location_data.group],
				{ location_data.order, location_name, location_link, formatted_synonyms })
		end
	end
	
	for _, variety in ipairs(variety_list) do
		local colour = variety_colour[variety]
		if #template[variety] > 0 then
			table.sort(template[variety], function(first, second) return first[1] < second[1] end)
			for i, point_data in ipairs(template[variety]) do
				table.insert(syn_table, "\n|-")
				if i == 1 then
					table.insert(syn_table, "\n!rowspan=" .. #template[variety] .. (special_note[variety] and " colspan=2" or "") .. 
					' style="background:#' .. colour .. '"| ' .. (special_note[variety] or variety_list_vi[_]))
				end
				table.insert(syn_table, ((point_data[2] and not special_note[variety]) and ('\n|style="background:#' .. colour .. '"| ' .. 
					'[[w:' .. point_data[3] .. '|' .. point_data[2] .. ']]') or '') ..
					'\n|style="background:#' .. colour .. '"| ' ..
					table.concat(point_data[4], ", "))
			end
		end
	end

	if note and note ~= "" then
		table.insert(syn_table, '\n|-\n! style="background:#FFF7FB; padding-top:5px; padding-bottom: 5px" | ' ..
			"<small>Ghi chú</small>\n| colspan=2|<small><i>" .. note .. "</i></small>")
	end
	
	table.insert(syn_table, '\n|}</div></div>')
	
	return table.concat(syn_table, "")
end

return export