local export = {}
local links = require("Module:links")
local lang = require("Module:languages")
local m_data = require("Module:zh-forms/data")
local find = mw.ustring.find
local gsub = mw.ustring.gsub
local match = mw.ustring.match
local len = mw.ustring.len

local sc = {
	["trad"] = "Hant",
	["simp"] = "Hans",
	["both"] = "Hani",
}

-- Change one variant character to another variant character.
-- Currently, only do so once. Return false if there is more than one character to change, or if there is no change.
function export.change_to_variant(text)
	local count = 0
	local text = mw.ustring.gsub(text, ('([%s])'):format(m_data.chars_variant_both), function(char)
		count = count + 1
		if (count > 1) then return '' end -- add |t2= manually, please
		local this_char_index = mw.ustring.find(m_data.chars_variant_both, char)
		local first_or_second = (this_char_index % 2)
		local other_char_index = this_char_index + (first_or_second == 1 and 1 or -1)
		return mw.ustring.sub(m_data.chars_variant_both, other_char_index, other_char_index)
	end)
	return (count == 1 and text or '')
end

local zh_link_impl = nil
local function zh_link(...)
	if zh_link_impl == nil then
		zh_link_impl = require("Module:zh/link")
	end
	return zh_link_impl.link(unpack(arg))
end

function export.make(frame)
	local params = {
		[1] = { list = true, allow_holes = true, allow_empty = true },
		["s"] = { list = true },
		["t"] = { list = true },
		["ss"] = {}, ["ns"] = {}, ["alt"] = {}, ["type"] = {}, ["delink"] = {}, ["lit"] = {}, ["note"] = {}, ["gloss"] = {}, ["align"] = {}
	}
	local args = require("Module:parameters").process(frame:getParent().args, params)
	local comp_type = args["type"]
	local s, t = {}, {}
	local annotation = {}
	if not frame:getParent().args["t"] then
		table.insert(t, 1, mw.title.getCurrentTitle().subpageText)
	end
		
	local PAGENAME = mw.title.getCurrentTitle().text
	local content = mw.title.new(PAGENAME):getContent()
	
	local function insert_st(set, text)
		table.insert(set, text)
	end
	
	for i = 1, #args.s do
		if (#args.s == 1) and PAGENAME == args.s[i] then error('Redundant text in |s=.') end
		insert_st(s, args.s[i])
	end
	for i = 1, #args.t do
		if (#args.t == 1) and PAGENAME == args.t[i] then error('Redundant text in |t=.') end
		insert_st(t, args.t[i])
	end
	
	-- temp tracking
	if #s == 0 and (gsub(t[1], '.', mw.loadData("Module:zh/data/ts").ts)) ~= t[1] then
		require('Module:debug').track('zh-forms/entry possibly missing a simplified form')
	end
	if #t == 1 then
		local to_variant = export.change_to_variant(t[1])
		if (to_variant ~= '') then
			-- automatically generate a |t2=
			insert_st(t, export.change_to_variant(t[1]))
		elseif find(t[1], ('[%s]'):format(m_data.chars_variant_both .. m_data.chars_variant_one)) then
			require('Module:debug').track('zh-forms/entry possibly missing a variant form')
		end
	end
	s.name = "simp"
	t.name = "trad"
	
	if #t ~= 1 and #s == 0 then
		table.insert(s, t[1])
	end

	local function asterisk(term, iscomp)
		if iscomp and len(t[1]) > 1 then return "" end
		if term == mw.title.getCurrentTitle().subpageText or not (mw.title.new(term) or {}).exists then return "" end
		local content = mw.title.new(term):getContent()
		content = gsub(content, "zh%-pron", "Ꙁ")
		content = gsub(content, "zh%-see", "Ꙁ")
		content = gsub(content, "[^Ꙁ]", "")
		return mw.ustring.len(content) > 1 and '<sup><span class="explain" title="This form has one or more other meanings.">*</span></sup>' or ''
	end

	local function var_fmt(length, color)
		return '\n|-\n! style="padding: 0.' .. (length > 8 and '3' or '5') ..
			'em;border: 1px solid #aaa;background: #' .. (color or 'E0FFFF') ..
			';font-weight: normal;font-size: smaller;" colspan="2" |'
	end
	
	local function char_gap(length, script, last)
		return '\n| style="padding: 0.' .. (length > 8 and '3' or '5') ..
			'em; background-color:white;' ..
			(last and 'border-right: 1px solid #aaa;border' .. (length ~= 1 and '-bottom' or '') .. ': 1px solid #aaa; '
				or 'border-bottom: 1px solid #aaa; ') ..
			'font-size:x-large" lang="zh-' .. sc[script] .. '" class="' .. sc[script] .. '" | '
	end
	
	local function header(length, var_count)
		return ((length > 3 or var_count * length > 5 or args.align == 'left') and '{|' or '{| align=right') .. 
			' style="clear: right;margin: 1em;border-collapse: collapse;text-align: center"' ..
			(length ~= 1 and '\n|-\n! colspan=2|' or '')
	end
	
	local function gloss_fmt(word, colspan, length)
		return '\n! style="padding: 0.' .. (length > 8 and '3' or '5') ..
			'em;border: 1px solid #aaa;background:#F5F5DC;font-weight: normal;font-size: 85%; width:' ..
			(length <= 8 and (30 * word + 30) or (25 * word + 25)) .. 'px" colspan=' .. (colspan or 1)  ..'|'
	end

	local function form_fmt(text, length, script)
		local fmtd_text = {}
		for i,value in ipairs(text) do
			fmtd_text[i] = links.language_link({ lang = lang.getByCode("zh"), term = value }) .. asterisk(value, false)
		end
		return length ~= 1 and ((length > 8 and '' or '<span style="font-size:140%">') ..
			'(<span lang="zh-' .. sc[script] .. '" class="' .. sc[script] .. '">' .. table.concat(fmtd_text, "/") .. '</span>)' ..
			(length > 8 and '' or '</span>')) or ''
	end
	
	local function char_fmt(text, length, script)
		return (#text ~= 1 and (char_gap(length, script) .. table.concat(text, char_gap(length, script), 1, #text-1)) or '') .. char_gap(length, script, true) .. text[#text]
	end
	
	local test_word = t[1]
	local length = len(test_word)
	local word_division = {}
	local i = 1
	local decomposable

	if comp_type then
		for index in mw.text.gsplit(comp_type, "", true) do
			if find(mw.ustring.sub(test_word, i, i), '[,%-]') then
				table.insert(word_division, { i, i } )
				i = i + 1
			elseif mw.ustring.sub(test_word, i, i) == '…' then
				table.insert(word_division, { i, i + 1 } )
				i = i + 2
			end
			table.insert(word_division, { i, i + index - 1 } )
			i = i + index
		end
		if i - 1 ~= len(gsub(test_word, '…+$', '')) and not find(table.concat(t) .. table.concat(s), "[⿰⿱⿲⿳⿴⿵⿶⿷⿸⿹⿺⿻]") then
			error("Parameter 'type' tidak sepadan dengan panjang perkataan.")
		end
	else
		for i = 1, length do
			table.insert(word_division, { i, i } )
		end
		decomposable = len(gsub(test_word, '…+$', '')) > 2 and true or false
	end
	
	local delink = {}
	if args["delink"] then
		if args["delink"] == "y" then
			for del_index, _ in ipairs(word_division) do
				delink[del_index] = "yes"
			end
		else
			for position in mw.text.gsplit(args["delink"], ",") do
				delink[tonumber(position)] = "yes"
			end
		end
	end
	
	local char_set = { ['simp'] = {}, ['trad'] = {} }
	local identity = #s == 0 and {t} or {s,t}
	local uncreated = {}
	
	for _, id in ipairs(identity) do
		for i, position in ipairs(word_division) do
			local char_string = ""
			for j = 1, #id do
				local word_form = mw.ustring.sub(id[j], position[1], position[2])
				if not find(char_string, word_form) then
					char_string = (char_string ~= "" and (char_string .. '/') or "") .. word_form
				end
			end
			if not find(char_string, '[,%-]') then
				local hash = {}
				for thing in mw.text.gsplit(char_string, (delink[i] and "" or "/")) do
					table.insert(hash, links.language_link({ lang = lang.getByCode("zh"), term = thing }) .. asterisk(thing, true))
				end
				char_string = table.concat(hash, (delink[i] and "" or "/"))
			end
			table.insert(char_set[id.name], char_string)
		end
		for _, item in ipairs(id) do
			if not (mw.title.new(item) or {}).exists and item ~= mw.title.getCurrentTitle().subpageText then
				table.insert(uncreated, '"[[' .. item .. ']]"')
			end
		end
	end

	local scripts = { ['一-鿿㐀-䶿﨎﨏﨑﨓﨔﨟﨡﨣﨤﨧-﨩𠀀-𪛟𪜀-𮯯𰀀-𱍏'] = 'Hani' , ['a-zA-ZāēīōūĀĒĪŌŪa-zA-Z'] = 'Latn', ['0-90-9'] = 'Numb', ['Ͱ-Ͽ'] = 'Grek' }
	local script = {}
	for range, script_name in pairs(scripts) do
		if find(test_word, '[' .. range .. ']') then
			table.insert(script, script_name)
		end
	end

	if find(t[1], "([^─…]+)%1") and args['gloss'] ~= '-' and len(t[1]) < 7 then
		if gsub(comp_type or "", "1", "") == "" then
			table.insert(annotation, '[[Kategori:Penggandaan bahasa Cina]]')
		elseif find(t[1], "([^…][^…]+)%1") or find(table.concat(char_set['trad'], " "), "([^─…%[%]a-z]+)%1") then
			local evil
			for _, component in ipairs(char_set['trad']) do
				if len(component) > 1 then
					local comp_content = mw.title.new(links.remove_links(component)):getContent() or false
					if not comp_content or find(comp_content, "|gloss=-") or not find(comp_content, "==Bahasa Cina==") then
						evil = true
					end
				end
			end
			if not evil then table.insert(annotation, '[[Kategori:Penggandaan bahasa Cina]]') end
		end
	end

	table.insert(annotation, #script > 1 and '[[Kategori:Istilah bahasa Cina yang ditulis dalam pelbagai skrip]]' or nil)
	table.insert(annotation, (decomposable and args['gloss'] ~= '-' and not args['note'] and not args['lit']) and '[[Kategori:Chinese entries with potentially decomposable titles]]' or nil)
	table.insert(annotation, (#uncreated > 0 and mw.title.getCurrentTitle().nsText == "") and '[[Kategori:Istilah bahasa Cina dengan bentuk yang tidak dibuat]]' .. 
		'<small class="attentionseeking">(' .. (#uncreated == 1 and 'This form' or 'These forms') ..
		' in the hanzi box ' .. (#uncreated == 1 and 'is' or 'are') .. ' uncreated: ' .. 
		table.concat(uncreated, ", ") .. '.)</small>' or nil)
	
	local ss = ""
	if args["ss"] then
		ss = var_fmt(length, 'FFFFE0') .. '[[w:Second round of simplified Chinese characters|2nd round simp.]]' .. mw.ustring.sub(char_gap(length, 'simp', true), 1, -45)
			.. '; padding-top: 10px; padding-bottom: 10px; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa"'
			.. ' colspan="' .. #word_division .. '"|' .. zh_link(nil, nil, { args["ss"], tr = "-" }, mw.title.getCurrentTitle().subpageText)
	end
	
	local ns = ""
	if args["ns"] then
		ns = var_fmt(length, 'FFFFE0') .. 'nonstandard simp.' .. mw.ustring.sub(char_gap(length, 'simp', true), 1, -45)
			.. '; padding-top: 10px; padding-bottom: 10px; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa"'
			.. ' colspan="' .. #word_division .. '"|' .. zh_link(nil, nil, { args["ns"], tr = "-" }, mw.title.getCurrentTitle().subpageText)
	end
	
	local altforms = ""
	if args["alt"] then
		local altform_list = {}
		for altform in mw.text.gsplit(args["alt"], ",") do
			local altdecomp = mw.text.split(altform, ":")
			local altdecomp2 = mw.text.split(altdecomp[1], "-")
			altdecomp3 = altdecomp2[2] and  ' <span style="font-size:70%"><i>' .. gsub(altdecomp2[2], "‡", frame:expandTemplate{
					title = "Template:zh-historical-dict",
					args = { type = "form", nocat = "1" }
				}) .. '</i></span>' or ''
			table.insert(altform_list, '<span style="white-space:nowrap;">' ..
				zh_link(nil, nil, { altdecomp2[1], tr = (altdecomp[2] or "-") }, mw.title.getCurrentTitle().subpageText) .. 
				altdecomp3 .. '</span>')
		end
		if #altform_list > 5 then
			altforms = '<div class="vsSwitcher" data-toggle-category="Chinese alternative forms"><span class="vsToggleElement">&nbsp;</span>' ..
				'<div class="vsShow">' .. table.concat(altform_list, "<br>", 1, 5) ..
				'</div><div class="vsHide">' .. table.concat(altform_list, "<br>") .. '</div></div>'
		else
			altforms = table.concat(altform_list, "<br>")
		end
		altforms = var_fmt(length, 'F0FFE0') .. 'alternative forms' .. mw.ustring.sub(char_gap(length, "trad", true), 1, -45)
			.. '; padding-top: 10px; padding-bottom: 10px; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa"'
			.. ' colspan="' .. #word_division .. '"|' .. altforms
	end
	
	local anagram = ""
	if len(t[1]) == 2 and not find(t[1], "(.)%1") then
		local anagram_link = mw.ustring.sub(t[1], 2, 2) .. mw.ustring.sub(t[1], 1, 1)
		local anagram_content = mw.title.new(anagram_link):getContent() or false
		if anagram_content and find(anagram_content, "==Chinese==") then
			anagram = var_fmt(length, 'F0FFE0') .. 'anagram' .. mw.ustring.sub(char_gap(length, 'trad', true), 1, -45)
			.. '; padding-top: 10px; padding-bottom: 10px; border-right: 1px solid #aaa; border-bottom: 1px solid #aaa"'
			.. ' colspan="' .. #word_division .. '"|' .. zh_link(nil, nil, { anagram_link, tr = "-" }, mw.title.getCurrentTitle().subpageText)
		end
	end
	
	local literal = (args["lit"] or args["note"]) and '\n|-' .. 
		gloss_fmt(length, #word_division + 2, length) .. 
		(args["lit"] and '<i>Harfiah:</i> “' .. args["lit"] .. 
		(find(args["lit"], "%.$") and "”" or "”.") or args["note"]) or ""
	
	local gloss = {}
	if args['gloss'] == '-' then
		gloss = { gloss_fmt(length * 1.6, #word_division, length) .. '<i>phonetic</i>' }
	elseif length == 1 then
		gloss = {}--{ gloss_fmt(1.6, #word_division) .. '-' }
	else
		for i, position in ipairs(word_division) do
			local character = mw.ustring.sub(t[1], position[1], position[2])
			
			local gloss_text = args[1][i]
			-- Load glosses module if no gloss was supplied and the word is a single character.
			if not gloss_text and position[1] == position[2] then
				local glosses = mw.loadData("Module:zh/data/glosses")
				gloss_text = glosses.glosses[character] or ""
				gloss_text = gsub(gloss_text, "{{taxlink|([^{}]+)}}",
					function (taxlink_text)
						local taxlink_args, argi = {}, 1
						for arg in mw.text.gsplit(taxlink_text, "|") do
							local arg_split = mw.text.split(arg, "=")
							if arg_split[2] then
								taxlink_args[arg_split[1]] = arg_split[2]
							else
								taxlink_args[argi] = (arg ~= "" and arg or nil)
								argi = argi + 1
							end
						end
						local frame = mw.getCurrentFrame()
						return frame:expandTemplate{
							title = 'taxlink',
							args = taxlink_args
						}
					end)
				if gloss_text == "" and find(character, "^[一-鿿㐀-䶿﨎﨏﨑﨓﨔﨟﨡﨣﨤﨧-﨩]+$") and not find(glosses.nonlemma, character) then
					require('Module:debug').track('zh-forms/no gloss found for Chinese character')
				end
			end
			if gloss_text == "-" then gloss_text = "''phonetic''" end
			if not gloss_text then
				gloss_text = ""
			end
			
			--[[
				To ensure that suffixes are not broken up between lines, like this:
				-
				ist
			]]
			if find(gloss_text, "-", nil, true) then
				local nonbreaking_hyphen = mw.ustring.char(0x2011)
				gloss_text = mw.ustring.gsub(gloss_text, "^%-", nonbreaking_hyphen)
				gloss_text = mw.ustring.gsub(gloss_text, "(%s)%-", "%1" .. nonbreaking_hyphen)
			end
		
			if gloss_text == "" and position[2] > position[1] then
				local senses = {}
				local content = mw.title.new(character):getContent() or false
				if content then
					gloss_text = require("Module:zh/extract").extract_gloss(content, false)
					if gloss_text == "" and find(character, "^[一-鿿㐀-䶿﨎﨏﨑﨓﨔﨟﨡﨣﨤﨧-﨩]+$") then
						require('Module:debug').track('zh-forms/no gloss found but entry exists')
					end
					if not string.match(content, character) then
						require('Module:debug').track('zh-forms/compounds not mentioned in derived terms on the component pages')
					end
				else
					if gloss_text == "" and find(character, "^[一-鿿㐀-䶿﨎﨏﨑﨓﨔﨟﨡﨣﨤﨧-﨩]+$") then
						table.insert(annotation, '[[Category:Chinese redlinks/zh-forms]]')
					end
				end
			end
			gloss_text = gsub(gloss_text, ";[^a-zA-Z0-9]+;", ";")
			gloss_text = gsub(gloss_text, ";[^a-zA-Z0-9]*$", "")
			gloss_text = gsub(gloss_text, ";+", ";")
			if len(gsub(gloss_text, '[^;]', '')) > 2 then
				gloss_text = '<div class="vsSwitcher" data-toggle-category="glosses"><span class="vsToggleElement">&nbsp;</span><div class="vsShow">' ..
					match(gloss_text, '^[^;]+;[^;]+;[^;]+') .. '</div><div class="vsHide">' .. gloss_text .. '</div></div>'
			end
			local word_length = match(character, '[,…%-]') and 0 or 
				(delink[i] and len(character) or len(character) * (len(gsub(char_set['trad'][i], '[^/]', '')) + 1))
			table.insert(gloss, gloss_fmt(word_length, 1, length) .. gloss_text)
		end
	end
	
	if content then
		local applicable_pos = { ["Kata nama"] = 1, ["Kata kerja"] = 1, ["Kata sifat"] = 1, ["Kata keterangan"] = 1, 
			["Definisi"] = 1, ["Sebutan"] = 1 }
		local previous_level = 2
		local subheading_wanted
		--[=[
		-- Used under headers for Chinese varieties, for instance in [[āu-piah]]
		local Chinese_section = string.match(content, "\n==Chinese==\n(.-)\n==[^=]")
		if not Chinese_section then
			error("No Chinese section found.")
		end
		--]=]
		if length == 1 and not string.match(content, "===Definitions===") then
			require('Module:debug').track('zh-forms/no definitions section found')
		end
		if length == 1 and not string.match(content, "===Compounds===") and string.match(content, "zh-der") then
			require('Module:debug').track('zh-forms/derived terms probably needing renaming')
		end
		for equals, heading_text in string.gmatch(content, "\n(%=%=+)([^%=]+)%=%=+") do
			local current_level = #equals
			if subheading_wanted and current_level ~= previous_level + 1 then
				if applicable_pos[heading_text] then
					error("Tajuk kepala \"===Etimologi ''n''===\" or \"===Sebutan ''n''===\" mesti diikuti subkepala satu tahap yang lebih rendah.")
				end
			end
			previous_level = current_level
			subheading_wanted = string.find(heading_text, " [0-9]+") and true or false
		end
	end
	
	local simp_note = ""
    --This is not a complete list!
	
	if #identity == 1 and find(m_data.chars_unified, '[' .. test_word .. ']') then
		simp_note = '<sup><span class="explain" title="Using the same code point' .. (length>1 and 's' or '') .. ' as the traditional form due to Han unification. Without proper font support, it may be displayed as the same as the traditional form.">#</span></sup>'
		char_set['simp'] = char_set['trad']
	end
	
	return table.concat{
		header(length, math.max(#t, #s)), table.concat(gloss, ""),
		((#identity == 1 and simp_note == '') and
			(var_fmt(length) .. '[[Bahasa Cina Ringkas|ringkas]] dan [[Bahasa Cina Tradisional|trad.]]<br>' .. 
				form_fmt(t, length, 'both') .. char_fmt(char_set['trad'], length, 'both'))
		or
			 var_fmt(length) .. '[[Bahasa Cina Tradisional|trad.]] ' .. 
			 	form_fmt(t, length, 'trad') .. char_fmt(char_set['trad'], length, 'trad') .. 

			(var_fmt(length) .. '[[Bahasa Cina Ringkas|ringkas]] ' .. simp_note ..
				form_fmt(#s == 0 and t or s, length, 'simp') .. char_fmt(char_set['simp'], length, 'simp'))

		), ss, ns, altforms, anagram, literal, '\n|}', table.concat(annotation)
	}
end

return export