local concat = table.concat
local insert = table.insert
local load_data = mw.loadData
local new_title = mw.title.new
local process_params = require("Module:parameters").process

local data = load_data("Module:zh/data/glyph-data")

local export = {}

function export.main(frame)
	local boolean = {type = "boolean"}
	local args = process_params(frame:getParent().args, {
		[1] = true,
		["no_img"] = boolean,
		["no_phon"] = boolean,
	})
	
	local target_page = args[1] or load_data("Module:headword/data").pagename
	local showEras, showScripts, showImgs, hideText = {}, {}, {}, {}
	local success, data_module = pcall(load_data, "Module:zh/data/glyph-data/" .. target_page)

	local char_data = {
		["bronze"] = {},
		["oracle"] = {},
		["silk"] = {},
		["slip"] = {},
		["seal"] = {},
		["bigseal"] = {},
	}

	local count = 0
	if not args.no_img then
		for _, era in ipairs(data.eras) do
			local count_era = 0
			for _, script in ipairs(era[2]) do
				local img_link = target_page .. "-" .. script .. ".svg"
				local img_file = new_title("Media:" .. img_link)
				if img_file.exists and not img_file.isRedirect then
					count = count + 1
					count_era = count_era + 1
					insert(showScripts, "\n!" .. data.scripts[script])
					insert(showImgs, "\n| style=\"padding: 8px;\"|[[File:" .. img_link .. "|60px]]")
				end
			end
			if count_era > 0 then
				insert(showEras, "\n! colspan=\"" .. count_era .. "\"|" .. era[1])
			end
		end
	end
	if success then
		local img_count = 0
		for _ in ipairs(data_module[1]) do
			img_count = img_count + 1
		end
		success = success and new_title("Media:ACC-" .. data_module[1][img_count] .. ".svg").exists
	end
	if success then
		for _, img in ipairs(data_module[1]) do
			insert(char_data[data.script_abbrev[img:match("^.[\128-\191]*")]], '<div class="gallerybox" style="display:inline-block"' ..
				'><div style="text-align:center">[[File:ACC-' .. img ..
				'.svg|60px]]<div class="gallerytext"><small>' .. img .. '</small></div></div></div>')
		end
		for i, script in ipairs(data.hide_scripts) do
			if char_data[script][1] then
				if i ~= 1 then
					insert(hideText, "<hr>")
				end
				insert(hideText, "<div class=\"gallery\"><div><b>" .. data.scripts[script] .. "</b></div>" .. concat(char_data[script]) .. "</div>")
			end
		end
		insert(hideText, '\n|- class="vsHide"\n| width="100%" align="left" colspan="' .. (count == 0 and 1 or count) ..
			'|\n<div class="toccolours mw-collapsible mw-collapsed"><b>參考</b>:' ..
			'<div class="mw-collapsible-content">\n主要來自[[w:理查德·西尔斯 (学者)|理查德·西爾斯]]的' ..
			"[http://hanziyuan.net/#" ..
			target_page .. " 漢字字源網]([[c:Commons:Ancient Chinese characters/Richard Sears Agreement" ..
			"|允許使用說明]]),<br>收集來自不同形式的古文字的繪圖資料" ..
			",包括:\n* 《說文解字》(小篆)\n* 《金文編》(金文)" ..
			"\n* 《六書通》(傳抄古文字)\n* 《殷墟甲骨文編》(甲骨文)</div></div>")
	end
	
	local glyph_forms
	if ( success or count > 0 ) and not args.no_img then
		glyph_forms = "<div style=\"overflow:auto;width:fit-content;max-width:100%\">\n" .. [=[{| class="wikitable zh-glyph]=] .. (success and ' vsSwitcher" data-toggle-category="forms' or "") ..
			[=[" cellpadding=7 style="border-spacing: 1px; border: 1px solid darkgray; text-align:center"
			! class="vsToggleElement" colspan="]=] .. (count == 0 and 1 or count) ..
			[=[" |古代字體(<span lang="zh-Hant" class="Hani">-{]=] .. target_page .. [=[}-</span>)]=] ..

			(count > 0
				and "\n|-" .. concat(showEras) .. "\n|-" .. concat(showScripts) .. "\n|-" .. concat(showImgs)
				or "") ..

			(success
				and "\n|- class=\"vsHide\"\n| align=\"center\" colspan=\"" .. (count == 0 and 1 or count) ..
					"|" .. concat(hideText, "")
				or "") ..

			"\n|}\n</div>"

	else
		glyph_forms = ""
	end

	local phonText = {}
	local list = load_data("Module:zh-glyph/phonetic/list")
	local phonComp = list[target_page] or nil

	if phonComp and not args.no_phon then
		insert(phonText,
			'\n' ..
			'<div class="NavFrame" style="border:0px; max-width: 37em; text-align:center;" cellpadding="6">' ..
			'<div class="NavHead" style="font-size:105%; border:1px solid #aaaaaa; background-color:#CCCCFF; text-align:center;" cellpadding="3">' ..
			'[[Wiktionary:關於漢語/諧聲系|同聲符字]]' ..
			' (<span class="Hani">-{[[' .. phonComp .. ']]}-</span>)' ..
			' <small>([[Wiktionary:關於漢語/參考文獻|鄭張尚芳 (2003)]])</small>&nbsp; ' ..
			'</div>' ..
			'<div class="NavContent">' ..
			'\n{| class="wikitable zh-glyph" style="margin-top: 0; width: 100%; display: table;"' ..
			'\n|-\n! align="center"|\n!上古漢語'
		)

		local phonData = load_data("Module:zh-glyph/phonetic")
		local m_och = require("Module:och-pron").retrieve_pron
		
		for item in phonData[phonComp]:gmatch(".[\128-\191]*") do
			insert(phonText, '\n|-\n| align="center" |<span class="Hani">-{[[' .. item .. '#漢語|' .. item .. ']]}-</span>')
			local IPA = m_och(item, nil, true)
			if IPA then
				insert(phonText, '\n|<small><span class="IPA">' .. IPA .. '</span></small>')
			end
		end
		insert(phonText, '\n|}\n</div></div>')
	end

	return glyph_forms .. concat(phonText)
end

return export