local export = {}

local m_IPA = require("Module:IPA")
local lang = require("Module:languages").getByCode("emx")
local rsub = mw.ustring.gsub
local rlower = mw.ustring.lower

local V = "[aeiouy]"

local phon = {
	['ñ']='ɲ', ['g'] = 'ɡ', ['ü'] = 'y'
}

local function phonetic(text)
	text = rlower(text)
	text = rsub(text, ".", phon)
	-- digraphs
	text = rsub(text, "tx", "t͡ʃ")
	text = rsub(text, "ll", "ʎ")
	text = rsub(text, "tz", "ц")
	text = rsub(text, "ts", "đ")
	-- sibilants
	text = rsub(text, "x", "ʃ")
	text = rsub(text, "s", "с")
	text = rsub(text, "z", "з")
	text = rsub(text, "с", "s̺")
	text = rsub(text, "з", "s̻")
	
	text = rsub(text, "ц", "t͡s̻")
	text = rsub(text, "đ", "t͡s̺")
	
	--rhotics
	text = rsub(text, "(" .. V .. ")r(" .. V .. ")", "%1ɾ%2")
	text = rsub(text, "rr", "r")
	
	--diphthongs
	text = rsub(text, "([aeouy])i", "%1i̯")
	text = rsub(text, "([aeo])u", "%1u̯")

	return text
end

function export.IPA(frame)
	local words = {}
	
	for _, word in ipairs(frame:getParent().args) do
		table.insert(words, word)
	end
	
	if #words == 0 then
		words = {mw.title.getCurrentTitle().text}
	end
	
	local IPA_results = {}
	
	for _, word in ipairs(words) do
		table.insert(IPA_results, { pron = "/" .. phonetic(word) .. "/" })
	end
	
	return "* " .. m_IPA.format_IPA_full{ lang = lang, items = IPA_results}
end

return export