local lang = require("Module:languages").getByCode("bug")

local export = {}
local pos_functions = {}

local u = mw.ustring.char

-----------------------
-- Utility functions --
-----------------------

-- If Not Empty
local function ine(arg)
    if arg == "" then
        return nil
    else
        return arg
    end
end

local function list_to_set(list)
    local set = {}
    for _, item in ipairs(list) do set[item] = true end
    return set
end

-- version of mw.ustring.gsub() that discards all but the first return value
function rsub(term, foo, bar)
    local retval = mw.ustring.gsub(term, foo, bar)
    return retval
end

local function make_unused_key_tracker(t)
	local unused_keys = require "Module:table".listToSet(require "Module:table".keysToList(t))
	local mt = {
		__index = function(self, key)
			if key ~= nil then
				unused_keys[key] = nil
			end
			return t[key]
		end,
		__newindex = function(self, key, value)
			t[key] = value
		end
	}
	local proxy_table = setmetatable({}, mt)
	return proxy_table, unused_keys
end

local rfind = mw.ustring.find

local function append_cat(data, pos)
    table.insert(data.categories, lang:getCanonicalName() .. pos)
end

function remove_links(text)
    text = rsub(text, "%[%[[^|%]]*|", "")
    text = rsub(text, "%[%[", "")
    text = rsub(text, "%]%]", "")
    return text
end

local function otherscript(inflections, args)
    local title = mw.title.getCurrentTitle()
    local sc = lang:findBestScript(title.subpageText)

    local other_sc

    if sc:getCode() == "Latn" then
        other_sc = require("Module:scripts").getByCode("Bugi")
        local inflection = {label = "隆塔拉文"}

        if not tr then
            tr = require("Module:bug-translit").tr(
                     require("Module:links").remove_links(
                         mw.title.getCurrentTitle().text), "bug", sc:getCode())
        end

        table.insert(inflection, {term = tr, sc = other_sc})

        table.insert(inflections, inflection)
    end
end

-- The main entry point.
function export.show(frame)

    local PAGENAME = mw.title.getCurrentTitle().text

    local poscat = frame.args[1] or error(
                       "Part of speech has not been specified. Please pass parameter 1 to the module invocation.")

    local params = {
        [1] = {list = "head", allow_holes = true, default = ""},
        ["head"] = {default = ""}
    }

	local args, unused_keys = make_unused_key_tracker(frame:getParent().args)

    -- Gather parameters
    local data = {
        lang = lang,
        pos_category = poscat,
        categories = {},
        heads = {},
        translits = {},
        inflections = {}
    }

    otherscript(data.inflections, args)

    if pos_functions[poscat] then pos_functions[poscat].func(args, data) end

    local unused_key_list = require"Module:table".keysToList(unused_keys)
    if #unused_key_list > 0 then
        local unused_key_string = require "Module:array"(unused_key_list):map(
                                      function(key)
                return "|" .. key .. "=" .. args[key]
            end):concat("\n")
        error("Unused arguments: " .. unused_key_string)
    end

    return require("Module:headword").full_headword(data)
end

local function getargs(args, argpref, position)
    -- Gather parameters
    local forms = {}

    if ine(args[position]) then
        form = ine(args[position])
    else
        form = ine(args[argpref])
    end

    local i = 1

    while form do

        table.insert(forms, {term = form})

        i = i + 1
        form = ine(args[argpref .. i])
    end

    return forms
end

local function handle_infl(args, data, argpref, label, position)
    local newinfls = getargs(args, argpref, position)
    newinfls.label = label

    if #newinfls > 0 then table.insert(data.inflections, newinfls) end
end

return export