local export = {}

local Array = require("Module:array")
local m_lang = require("Module:languages")

-- Allows us to get the language object for the longest language code
-- in a template name.
-- For instance, when given "cel-bry-noun", where "cel-bry" yields
-- Proto-Brythonic and "cel" yields Proto-Celtic, Proto-Brythonic wins out.
local function get_from_hyphenated_prefix(title, getter)
    local segments = {}
    for segment in title:gmatch "[^-]+" do
        table.insert(segments, segment)
    end
    local object
    for i = #segments - 1, 1, -1 do
        local code = table.concat(segments, "-", 1, i)
        object = getter(code)
        if object then
        	local rest = table.concat(segments, "-", i + 1)
        	if rest == "" then rest = nil end
        	return object, rest
        end
    end
end

function export.categorize(title, sortkey)
	local name = title.text
		local lang_obj, rest = get_from_hyphenated_prefix(
			title.text,
			function(code)
				return m_lang.getByCode(code) or m_lang.getByCode(code .. "-pro") or m_lang.getByCode("inc-" .. code)
			end
			)
	
	sortkey = sortkey or rest or name
	
	--return "[[Category:" .. lang_obj:getCanonicalName()
	--	.. " headword-line templates|" .. sortkey .. "]]"
	return "[[หมวดหมู่:แม่แบบบรรทัดคำหลัก" .. lang_obj:getCategoryName()
		.. "|" .. sortkey .. "]]"
end

function export.main(frame)
	local current_title = mw.title.getCurrentTitle()
	if current_title.nsText == "" or current_title.nsText == "การสืบสร้าง" then
		error("This template is meant to be used in the Template namespace.")
	end
	
	local args = frame:getParent().args
	
	local title = current_title
	local is_demo = current_title.nsText == "มอดูล"
		or (current_title.nsText == "แม่แบบ"
		and current_title.baseText == "headword-line template cat")
	if is_demo and args.title then
		title = mw.title.new(args.title)
	end
	
	local categories = export.categorize(title, args.sort)
	if is_demo then
		categories = mw.text.nowiki(categories)
	end
	
	return categories
end

return export