local export = {}

local lang = require("Module:languages").getByCode("lif")
local sc = require("Module:scripts").getByCode("Limb")
local m_IPA = require("Module:IPA")

local gsub = mw.ustring.gsub
local gmatch = mw.ustring.gmatch
local find = mw.ustring.find

local correspondences = {
	["ṅ"] = "ŋ", ["g"] = "ɡ", ["k"] = "k", 
    ["p"] = "p", ["b"] = "b", ["c"] = "t͡ɕ", 
    ["j"] = "dʑ", ["ñ"] = "ɲ", ["t"] = "t",
    ["d"] = "d", ["y"] = "j", ["w"] = "w",
    ["l"] = "l", ["s"] = "s", ["ś"] = "ʃ", 
    ["ṣ"] = "s", ["h"] = "ɦ", ["n"] = "n",  
    ["ṃ"] = "̃", ["’"] = "ˀ", ["r"] = "r",
    ["ṭ"] = "t", ["ḍ"] = "d", ["ṇ"] = "ɳ", 

	["a"] = "a", ["i"] = "i", ["u"] = "u", 
    ["e"] = "e", ["o"] = "o", ["ê"] = "ɛ", 
    ["ô"] = "ɔ", 

    ["ā"] = "aː", ["ī"] = "iː", ["ū"] = "uː", 
    ["ē"] = "eː", ["ō"] = "oː", 
    

          [" "] = " ", [","] = ",", ['̄'] = 'ː',
}

local vowels = "aiueoôêɔɛaːāīūēōô̄ê̄ˑ"
local weak_h_c = "gjdṇḍbvrṟwy"
local primary_stress = "ˈ"
local secondary_stress = "ˌ"
local weak_h = "([" .. weak_h_c .. "])h"
local aspirate = "([kcṭtp])"
local syllabify_pattern = "([" .. vowels .. "]̃?)([^" .. vowels .. "%.%-]+)([" .. vowels .. "]̃?)"

local function find_consonants(text)
	local current = ""
	local cons = {}
	for cc in mw.ustring.gcodepoint(text .. " ") do
		local ch = mw.ustring.char(cc)
		if find(current .. ch, "^[kgṅcjñṭḍṇɽtdnpbmɽ̃yrlɳwvɾjwśṣshqxġzžḻṛṟfθðṉ]$") or find(current .. ch, "^[kgcjṭḍṇtɽdɽ̃pbṛṟ]h$") then
			current = current .. ch
		else
			table.insert(cons, current)
			current = ch
		end
	end
	return cons
end

local function syllabify(text)
	for count = 1, 2 do
		text = gsub(text, syllabify_pattern, function(a, b, c)
			b_set = find_consonants(b)
			table.insert(b_set, #b_set > 1 and 2 or 1, ".")
			return a .. table.concat(b_set) .. c
			end)
		text = gsub(text, "(" .. vowels .. ")(?=" .. vowels .. ")", "%1.")
	end
	for count = 1, 2 do
		text = gsub(text, "(" .. vowels .. ")(" .. vowels .. ")", "%1.%2")
	end
	return text
end

local identical = "knlsfzθð"
for character in gmatch(identical, ".") do
	correspondences[character] = character
end

local function transliterate(text)
	return lang:transliterate(text)
end

function export.link(term)
	return require("Module:links").full_link{ term = term, lang = lang, sc = sc }
end

function export.toIPA(text, phonetic)
	local translit = transliterate(text)
	if not translit then
		error('Kata "' .. Limbu .. '" tidak dapat ditransliterasikan.')
	end

	if phonetic then
translit = gsub(translit, "([eo])", "%1ˑ")
translit = gsub(translit, '([aāêôeēoōiīuū])([aāêôeēoōiīuū])', '%1ʔ%2')
translit = gsub(translit, '([êô]̄)([aāêôeēoōiīuū])', '%1ʔ%2')
translit = gsub(translit, '([aāêôeēoōiīuū])([êô]̄)', '%1ʔ%2')
	end

	local result = gsub(translit, ".", correspondences)
translit = gsub(translit, '([aāêôeēoōiīuū])([aāêôeēoō])', '%1.%2')
translit = gsub(translit, '([aāeēoōiīuū])([iīuūeēoō])', '%1.%2')
translit = gsub(translit, '([êô]̄)([aāêôeēoōiīuū])', '%1.%2')
translit = gsub(translit, '([aāêôeēoōiīuū])([êô]̄)', '%1.%2')
	   translit = gsub(translit, "*", "")
       translit = gsub(translit, "͠", "̃")
       translit = gsub(translit, "̃", "̃")
       translit = gsub(translit, '̄', 'ː')
       translit = gsub(translit, "%-", " ")
       translit = syllabify(translit)
	
	
	-- aspiration rules
	translit = gsub(translit, aspirate .. "h", '%1ʰ')
	translit = gsub(translit, weak_h, '%1ʱ')
	translit = gsub(translit, '([' .. weak_h_c .. '])%.h', '.%1ʱ')
	translit = gsub(translit, aspirate .. '%.h', '.%1ʰ')
    translit = gsub(translit, "%.ː", "ː.")

	local result = gsub(translit, ".", correspondences)
	
	-- formatting
	result = gsub(result, "ː̃", "̃ː")
	result = gsub(result, "ː.̃", "̃ː.")
    result = gsub(result, "%.$", " ")
    result = gsub(result, "([āā])", "aː")
    result = gsub(result, "%.?%-", ".")
	result = gsub(result, "ː%.̃", "̃ː.")

	return result
end

function export.make(frame)
	local args = frame:getParent().args
	local pagetitle = mw.title.getCurrentTitle().text
	
	local p, results = {}, {}
	
	if args[1] then
		for index, item in ipairs(args) do
			table.insert(p, (item ~= "") and item or nil)
		end
	else
		p = { pagetitle }
	end
	
	for _, Limbu in ipairs(p) do
		table.insert(results, { pron = "/" .. export.toIPA(Limbu) .. "/" })
		if export.toIPA(Limbu, true) ~= export.toIPA(Limbu) then
			table.insert(results, { pron = "[" .. export.toIPA(Limbu, true) .. "]" })
		end
	end
	
	return m_IPA.format_IPA_full(lang, results)
end

return export