local export = {}

local m_links = require('Module:links')
local m_adj = require('Module:pl-adj')
local m_g = require('Module:gender and number')
local lang = require("Module:languages").getByCode("pl")

-- local consonants = "[bcćdfghjklłmnńpqrsśtvwxzżź]";

-- case information
local cases = {
	{ key = "nom"; en = "主格"; pl = "mianownik (kto? co?)" },
	{ key = "gen"; en = "屬格"; pl = "dopełniacz (kogo? czego?)" },
	{ key = "dat"; en = "與格"; pl = "celownik (komu? czemu?)" },
	{ key = "acc"; en = "賓格"; pl = "biernik (kogo? co?)" },
	{ key = "ins"; en = "工具格"; pl = "narzędnik (kim? czym?)" },
	{ key = "loc"; en = "方位格"; pl = "miejscownik (o kim? o czym?)" },
	{ key = "voc"; en = "呼格"; pl = "wołacz (o!)" },
}

-- columns for normal nouns
local noun_cols = {
	{ key = "s"; title = "單數" },
	{ key = "p"; title = "複數" },
}

-- columns for Old Polish nouns
local noun_dual_cols = {
	{ key = "s"; title = "單數" },
	{ key = "d"; title = "雙數" },
	{ key = "p"; title = "複數" },
}

-- columns for pronouns
local pronoun_cols = {
	{ key = "sm"; title = m_g.format_list({"m"}, lang) },
	{ key = "sf"; title = m_g.format_list({"f"}, lang) },
	{ key = "sn"; title = m_g.format_list({"n"}, lang) },
	{ key = "pm"; title = m_g.format_list({"vr-p"}, lang) },
	{ key = "po"; title = m_g.format_list({"nv-p"}, lang) },
}

local altsep = "/"

function empty_item(text)
	return (not text) or text == "" or text == "-" or text == "–" or text == "—"
end

-- add link markers, with links separated by any of splitchars
-- exported for use in testcases
-- normally the separator is altsep
function export.make_links(text, splitchars, title)
	if not title then
		title = mw.title.getCurrentTitle().fullText
	end
	if empty_item(text) then
		return "—"
	elseif not splitchars or splitchars == "" then
		return ("[[%s#波蘭語|%s]]"):format(text, text)
	else
		items = {}
		for word in mw.ustring.gmatch(text, "[^" .. splitchars .. "]+") do
			add_archaic = ""
			if word:sub(-string.len(" (archaic)")) == " (archaic)" then
				word = (mw.text.split(word, "% %(archaic%)"))[1]
				add_archaic = " (archaic)"
			end
			
			if word == title then
				table.insert(items, ("[[%s]]"):format(word) .. add_archaic)
			else
				table.insert(items, ("[[%s#波蘭語|%s]]"):format(word, word) .. add_archaic)
			end
		end
		
		if #items > 1 then
			require("Module:debug").track("pl-noun/splitchars")
		end
		
		return table.concat(items, "/")
	end
end

local function linkify_info(declinfo, splitchars, nolinks)
	if nolinks then
		require("Module:debug").track("pl-noun/nolinks")
	end
	
	local linked = {}
	local title = mw.title.getCurrentTitle().fullText
	for k, v in pairs(declinfo) do
		if v == title then
			linked[k] = "[[" .. v .. "]]"
		elseif nolinks then
			linked[k] = v
		else
			linked[k] = export.make_links(v, splitchars, title)
		end
	end
	return linked
end

local function nowiki_info(declinfo)
	require("Module:debug").track("pl-noun/nowiki")
	local nowikied = {}
	for k, v in pairs(declinfo) do
		nowikied[k] = mw.text.nowiki(v)
	end
	return nowikied
end

local function override_col_titles(heads, cols)
	if not heads then
		return cols or {}
	end
	local new_cols = {}
	local index = 1
	for word in mw.ustring.gmatch(heads, "[^,]+") do
		if cols[index] then
			table.insert(new_cols, { key = cols[index].key; title = word } )
		else
			table.insert(new_cols, { key = tostring(index); title = word } )
		end
		index = index + 1
	end
	for ci, col in ipairs(cols) do
		if ci >= index then
			table.insert(new_cols, cols[index])
		end
	end
	return new_cols
end

local function guess_width(declinfo, cols)
	local maxl = 0
	for k, v in pairs(declinfo) do
		local l = mw.ustring.len(mw.text.trim(v))
		if maxl < l then
			maxl = l
		end
	end
	local width = math.floor(maxl * 0.78) -- number obtained by anecdotal evidence
	width = (width < 10) and 10 or width
	width = 9 + (width * #cols)
	return width
end

-- generate the HTML code of an inflection table
-- each entry in heads must have "key" and "title"
local function make_table(declinfo, cols, preproc, width, title, nolinks, rnoms)
	local result = {}
	if not cols or not cols[1] then
		error("make_table: invalid cols parameter")
	end

	local lemma_key = cases[1].key .. cols[1].key
	local lemma = m_links.remove_links(declinfo[lemma_key])
	if rnoms then
	    lemma = '*' .. m_links.remove_links(rnoms)
	end
	
	title = title or ('<span class="Latn mention" lang="pl" xml:lang="pl">%s</span> 有紀錄的形式'):format(lemma)

	local emwidth = width or guess_width(declinfo, cols)

	if preproc == "nowiki" then
		declinfo = nowiki_info(declinfo)
	elseif preproc == "linkify" then
		declinfo = linkify_info(declinfo, altsep, nolinks)
	end

	if cols and (#cols > 0) then
		table.insert(result, '|-\n! style="background:#d9ebff; width: 8em;" |\n')
		for i, col in ipairs(cols) do
			table.insert(result, ('! style="background:#d9ebff;" scope="col" | %s\n'):format(col.title))
		end
	end

	local maxl = 0
	for i, case in ipairs(cases) do
		table.insert(result, ('|-\n! title="%s" style="background:#eff7ff;" scope="row" | %s\n'):format(case.pl, case.en))
		for _, col in ipairs(cols) do
			local declkey = case.key .. col.key
			local item = mw.text.trim(declinfo[declkey])
			if empty_item(item) then
				table.insert(result, '| —\n')
			else
				table.insert(result, ('| <span class="Latn" lang="pl" xml:lang="pl">%s</span>\n'):format(item))
			end
		end
	end

	local outtext = ([=[<div class="NavFrame" style="display: block;width: %uem;">
<div class="NavHead" style="background:#eff7ff" >%s</div>
<div class="NavContent">
{| style="background:#F9F9F9; text-align:center; width: %uem; margin: 0;" class="inflection-table"
]=]):format(emwidth, title, emwidth) .. table.concat(result, "") .. "|}</div></div>"

	return outtext
end

local function get_mode()
	local frame = mw.getCurrentFrame()
	if mw.isSubsting() then
		return 'subst'
	elseif frame:getParent():getTitle() == mw.title.getCurrentTitle().fullText then
		return 'demo'
	else
		return 'xclude'
	end
end

local function make_table_from_pargs(pargs, cols)
	local width = pargs.width and tonumber(pargs.width)
	
	local declinfo = {}
	
	cols = override_col_titles(pargs.heads, cols or {})
	for i = 1, 7 do
		for j, col in ipairs(cols) do
			local case_key = cases[i].key .. col.key
			local argn = ((i-1) * #cols) + j
			declinfo[case_key] = m_links.remove_links(mw.text.trim(pargs[case_key] or pargs[argn] or "-"))
		end
	end
	
	return make_table(declinfo, cols, "linkify", pargs.width, pargs.title, pargs.nolinks, pargs['rnoms'])
end

-- Generate declension table for a regular noun with all forms passed explicitly as parameters
function export.template_decl_noun(frame)
	local pargs = frame:getParent().args
	return make_table_from_pargs(pargs, noun_cols)
end

return export