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

local variety_list = {
	"Classical", "Formal", "Taxonomic",
	"北京-東北官話", "冀魯官話", "膠遼官話",
	"中原官話", "蘭銀官話",
	"西南官話", "江淮官話",
	"官話", "粵語", "贛語", "客家語", "徽語", "晉語", "九姓漁民船上話",
	"閩北語", "閩東語", "閩南語", "莆仙語", "閩中語", "邵將語", "中山閩語",
	"南部平話", "北部平話", "畲話", "瓦鄉話", "吳語", "湘語", "湘南土話", "粵北土話"
}

local variety_colour = {
	
	["Classical"]				= "FAF0F2",
	["Formal"]					= "FAF0F2",
	["Taxonomic"]				= "FAF0F2",
	["北京-東北官話"]	= "FAF5F0",
	["冀魯官話"]			= "FAF5F0",
	["膠遼官話"]		= "FAF5F0",
	["中原官話"]	= "FAF5F0",
	["蘭銀官話"]			= "FAF5F0",
	["西南官話"]	= "FAF5F0",
	["江淮官話"]		= "FAF5F0",
	["官話"]	= "FAF5F0",
	["粵語"]	= "F0F5FA",
	["贛語"]			= "F0FAF3",
	["客家語"]		= "FAF0F6",
	["徽語"]		= "FAF9F0",
	["晉語"]			= "F0F5FA",
	["九姓漁民船上話"]	= "FAF0FE",
	["閩北語"]		= "F7FAF0",
	["閩東語"]	= "F7FAF0",
	["閩南語"]		= "F7FAF0",
	["莆仙語"]	= "F7FAF0",
	["閩中語"]	= "F7FAF0",
	["邵將語"]	= "F7FAF0",
	["中山閩語"]	= "F7FAF0",
	["南部平話"]		= "F0F5FA",
	["北部平話"]		= "F0F5FA",
	["畲話"]		= "FAF0F6",
	["瓦鄉話"]			= "F0FAF6",
	["吳語"]			= "F4F0FA",
	["湘語"]		= "F0F2FA",
	["湘南土話"]	= "F0F9FA",
	["粵北土話"]	= "F0F9FA",
}

local special_note = {
	["Classical"] = "[[w:文言文|文言文]]",
	["Formal"] = "書面語 <small>([[w:官話白話文|白話文]])</small>",
	["Argot"] = "黑話",
	["Taxonomic"] = "分類學名稱",
}

function export.main(frame)
	local data = {}
	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 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
	
	--allow alternative title linking for sum-of-parts tables
	local title = m_syndata["title"] and m_syndata["title"] ~= "" and m_syndata["title"] or target_page
	
	local main_title = m_links.full_link( { term = title:gsub("[0-9%-]", "") .. "//", lang = zh, tr = "-" } )
	--判斷釋義是否含有拉丁字母
	local meaning_str = ''
	if not m_syndata["meaning"]:match('[A-Za-z]') then
		meaning_str = meaning_str .. '(「' .. m_syndata["meaning"] .. '」)'
	end
	local syn_table = { [=[
	<div class="NavFrame" 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">]=] ..
		main_title .. meaning_str .. '的各地方言用詞' ..
		"[[Template:zh-dial-map/" .. target_page .. '|<small>&#91;地圖&#93;</small>]]\n' .. [=[</div><div class="NavContent"> 
	{| class="wikitable" style="margin:0; text-align:center; width: 100%"
	|-
	! style="background:#E8ECFA" | 語言
	! style="background:#E8ECFA" | 地區
	! style="background:#E8ECFA" | 詞]=] .. [=[
	<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" })) ..
	' edit]</span></div>' }
	
	local note = m_syndata["note"]
	if m_syndata["Formal"][1] == "" then
		m_syndata["Formal"] = { target_page }
	elseif m_syndata["Formal"][1] == "-" then
		m_syndata["Formal"] = nil
	end

	local m_dialdata = require("Module:zh/data/dial")
	local variety = ""
	local current_variety = ""
	local location_name = ""
	local location_link = ""
	local colour = ""
	local exists = {}
	local variety_count = {}
	local formatted_synonyms = {}
	local loc = {}
	local cur = {}
	for i, v in pairs(variety_list) do
		variety_count[v] = 0
	end

	for i = 1,#m_dialdata,1 do
		loc = m_dialdata[i]
		cur = m_syndata[loc.key] or {""}
		if cur[1] == "" then
			exists[i] = false
		else
			exists[i] = true
			variety = loc.group
			variety_count[variety] = variety_count[variety] + 1
		end
	end
	
	for i = 1,#exists,1 do
		if exists[i] then
			loc = m_dialdata[i]
			variety = loc.group
			location_name = (loc.chinese or loc.key):gsub("(%(.*%))", "<small>%1</small>")
			location_link = loc.link or loc.chinese or loc.key
			formatted_synonyms = {}
			for i, synonym in ipairs(m_syndata[loc.key]) 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,
						tr = "-"
					} )
				if note == "GT" then
					require('Module:debug/track')("zh-dial-GT")
				end
				note = note and ' <span style="font-size:60%">' .. note .. '</span>' or ""
				table.insert(formatted_synonyms, synonym_link .. note)
			end
			table.insert(syn_table, "\n|-")
			if variety ~= current_variety then
				current_variety = variety
				colour = variety_colour[variety]
				table.insert(syn_table, "\n!rowspan=" .. variety_count[variety] .. (special_note[variety] and " colspan=2" or "") .. 
				' style="background:#' .. colour .. '"| ' .. (special_note[variety] or variety))
			end
			table.insert(syn_table,
				((location_name and not special_note[variety]) and ('\n|style="background:#' .. colour .. '"| ' .. 
				'[[w:' .. location_link .. '|' .. location_name .. ']]') or '') ..
				'\n|style="background:#' .. colour .. '"| ' ..
				table.concat(formatted_synonyms, "、"))
		end
	end
	
	if note and note ~= "" then
		table.insert(syn_table, '\n|-\n! style="background:#FFF7FB; padding-top:5px; padding-bottom: 5px" | ' ..
			"<small>註解</small>\n| colspan=2|<small>" .. note .. "</small>")
	end
	
	table.insert(syn_table, '\n|}</div></div>')
	
	return table.concat(syn_table, "")
end

return export