local find = mw.ustring.find
local rsub = mw.ustring.gsub
local u = require("Module:string/char")

local export = {}

local m_IPA = require("Module:IPA")
local lang = require("Module:languages").getByCode("kjp")

local V = "[ɑaæɒɔəɘʊeoɪiɨɯ]"
local S = u(0x032F) 		-- diphthong marker
local B = u(0x0324)			-- breathy voice

local phonemic = {
	["à"]="a1",	["ā"]="a2",	["á"]="a3",	["â"]="a4",
	["è"]="e1",	["ē"]="e2",	["é"]="e3",	["ê"]="e4",
	["ò"]="o1",	["ō"]="o2",	["ó"]="o3",	["ô"]="o4",
	["ɛ"]="æ",	["ɔ"]="ɒ",	["ə"]="ə",	["ʊ"]="ʊ",
	["ì"]="i1",	["ī"]="i2",	["í"]="i3",	["î"]="i4",
	["ɨ"]="ɨ",	["ɯ"]="ɯ",
}

local function phonetic(text)
	text = require("Module:kjp-translit").tr(text, lang, 'Mymr')
	-- vowels
	text = rsub(text, ".", phonemic)
	text = rsub(text, "([kcpt])h", "%1ʰ")
	text = rsub(text, "b", "ɓ")
	text = rsub(text, "d", "ɗ")
	text = rsub(text, "c", "t͡ɕ")
	-- tone 1
	text = rsub(text, "̀", "1")
	text = rsub(text, "̄", "2")
	text = rsub(text, "́", "3")
	text = rsub(text, "̂", "4")
	text = rsub(text, "ə([1234])", "ɘ%1")
	text = rsub(text, "([1234])" .. u(0x0331), u(0x0331) .. "%1")
	text = rsub(text, "i" .. u(0x0331), "ɪ")
	-- diphthong
	text = rsub(text, "(" .. V .. ")([1234])(" .. V .. "ɴ?)", "%1%3" .. S .. "%2")
	-- nasals
	text = rsub(text, "ɴ" .. S, S .. "ɴ")
	text = rsub(text, "(" .. V .. ")(" .. V .. S .. ")ɴ", "%1ɴ%2ɴ")
	text = rsub(text, "([1234])ɴ", "ɴ%1")
	text = rsub(text, S .. "ɴ", "ɴ" .. S)
	-- tone 2
	text = rsub(text, "1", "˩˩")
	text = rsub(text, "2", B .. "˧˧")
	text = rsub(text, "3", "˥˥")
	text = rsub(text, "4", "˥˩")
	-- phonetics
	text = rsub(text, "aɴ(" .. V .. ")", "ã%1")
	text = rsub(text, "aɴ", "ɑɴɔɴ" .. S)
	text = rsub(text, S .. B, B .. S)
	text = rsub(text, "ɴ" .. B, B .. "ɴ")
	text = rsub(text, "(" .. V .. "ɴ?)(" .. V .. B .. ")", "%1" .. B .. "%2")
	text = rsub(text, "ɴ", "̃")
	
	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