----------------------------------------------------------------------------------------------------
--                                                                                                --
--                                           NAMESPACE DETECT                                     --
--                                                                                                --
--      This module implements the {{namespace detect}} template in Lua, with a few               --
--      improvements: all namespaces and all namespace aliases are supported, and namespace       --
--      names are detected automatically for the local wiki. Function names can be configured     --
--      for different wikis by altering the values in the "cfg" table.                            --
--                                                                                                --
----------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------
--                                          Configuration data                                    --
--      Language-specific parameter names can be set here.                                        --
----------------------------------------------------------------------------------------------------

local cfg = {}

-- The name for the parameter to display content for the main namespace:
cfg.main = 'main'

-- The name for the parameter to display content in talk namespaces:
cfg.talk = 'talk'

-- The name for the parameter to display content for "other" namespaces (namespaces for which
-- parameters have not been specified, or for when cfg.demospace is set to cfg.other):
cfg.other = 'other'

-- The name for the parameter to set a demonstration namespace:
cfg.demospace = 'demospace'

-- The name for the parameter to set a specific page to compare:
cfg.page = 'page'

-- The header for the namespace column in the wikitable containing the list of possible
-- subject-space parameters.
cfg.wikitableNamespaceHeader = 'Namespace'

-- The header for the wikitable containing the list of possible subject-space parameters.
cfg.wikitableAliasesHeader = 'Aliases'

----------------------------------------------------------------------------------------------------
--                                       End configuration data                                   --
----------------------------------------------------------------------------------------------------

-- Declare the table of functions to return.
local p = {}

-- Get the page object. This will return the page object for the page specified, or nil if there are
-- errors in the title or if the expensive function count has been exceeded.
function p.getPageObject(page)
    if page then
        -- Get the page object, passing the function through pcall in case we are over the expensive
		-- function count limit.
        local noError, pageObject = pcall(mw.title.new, page)
        if not noError then
            return nil
        else
            return pageObject
        end
    else
        return mw.title.getCurrentTitle()
    end    
end

--[[ Returns a table of how parameter names map to namespace names. The keys are the actual namespace 
  names, in lower case, and the values are the possible parameter names for that namespace, also in
  lower case. The table entries are structured like this:
    [''] = {
        {'main'},
    },
    ['wikipedia'] = {
        {'wikipedia', 'project', 'wp'}
    }
]] 
function p.getParamMappings()
    local mappings = {}
    mappings[mw.ustring.lower(mw.site.namespaces[0].name)] = {cfg.main}
    mappings[cfg.talk] = {cfg.talk}
    for nsid, ns in pairs(mw.site.subjectNamespaces) do
        if nsid ~= 0 then -- Exclude main namespace.
            local nsname = mw.ustring.lower(ns.name)
            local canonicalName = mw.ustring.lower(ns.canonicalName)
            mappings[nsname] = {nsname}
            if canonicalName ~= nsname then
                table.insert(mappings[nsname], canonicalName)
            end
            for _, alias in ipairs(ns.aliases) do
                table.insert(mappings[nsname], mw.ustring.lower(alias))
            end
        end
    end
    return mappings
end

--[[ Create a wikitable of all subject namespace parameters, for documentation purposes. The talk 
  parameter is optional, in case it needs to be excluded in the documentation.
]]
function p.table(frame)
	-- Find whether to use the talk link or not.
    local useTalk = type(frame) == 'table' and type(frame.args) == 'table' and frame.args.talk == 'yes'

    -- Get the parameter mappings.
    local mappings = p.getParamMappings()
    
    -- Start the wikitable.
    local ret = '{| class="wikitable"'
        .. '\n|-'
        .. '\n! ' .. cfg.wikitableNamespaceHeader
        .. '\n! ' .. cfg.wikitableAliasesHeader
    
    -- Generate the row for the main namespace, as we want this
    -- to be first in the list.
    ret = ret .. '\n|-'
        .. '\n| <code>' .. cfg.main .. '</code>'
        .. '\n|'

    if useTalk then
        ret = ret .. '\n|-'
            .. '\n| <code>' .. cfg.talk .. '</code>'
            .. '\n|'
    end
        
    -- Enclose all parameter names in <code> tags.
    for ns, params in pairs(mappings) do
        if ns ~= mw.site.namespaces[0].name then
            for i, param in ipairs(params) do
                mappings[ns][i] = '<code>' .. param .. '</code>'
            end
        end
    end
    
    -- Generate the other wikitable rows.
    for ns, params in pairs(mappings) do
        if ns ~= mw.site.namespaces[0].name then -- Ignore the main namespace.
            ret = ret .. '\n|-'
                .. '\n| ' .. params[1]
                .. '\n| ' .. table.concat(params, ', ', 2)
        end
    end
    
    -- End the wikitable.
    ret = ret .. '\n|-'
        .. '\n|}'
    
    return ret
end

-- Gets the namespace name to compare to the arguments. The returned value is lower-case.
local function getNamespace(page, demospace)
    local ret
    if demospace then
        -- Handle "demospace = main" properly.
        if mw.ustring.lower(demospace) == cfg.main then
            ret = mw.site.namespaces[0].name
        else
            ret = demospace
        end
    else
        local pageObject = p.getPageObject(page)
        if pageObject then
            if pageObject.isTalkPage then
                -- {{namespace detect}} uses the same value for all talk namespaces, so that's what
				-- the module should do too.
                ret = cfg.talk
            else
                ret = pageObject.nsText
            end
        else
            return nil -- return nil if the page object doesn't exist.
        end
    end
    return mw.ustring.lower(ret)
end

-- Compare the namespace found with the parameters that have been specified, and return content of
-- the appropriate parameter.
function p._main(args)
    -- Get the namespace to compare the parameters to, and the parameter mapping table.
    local namespace = getNamespace(args[cfg.page], args[cfg.demospace])
    local mappings = p.getParamMappings()
    
    -- Check for any matches in the namespace arguments. The order we check them doesn't matter,
	-- as there can only be one match.
    for ns, params in pairs(mappings) do
        if ns == namespace then
            -- Check all aliases for matches. The default local namespace is checked first, as
			-- {{namespace detect}} checked these before alias names.
            for _, param in ipairs(params) do
                if args[param] then
                    return args[param]
                end
            end
        end
    end
    
    -- If there were no matches, return parameters for other namespaces. This happens if there
	-- was no text specified for the namespace that was detected or if the demospace parameter
	-- is not a valid namespace. Note that the parameter for the detected namespace must be
	-- completely absent for this to happen, not merely blank.
    if args[cfg.other] then
        return args[cfg.other]
    end
end

function p.main(frame)
    -- If called via #invoke, use the args passed into the invoking template, or the args
	-- passed to #invoke if any exist. Otherwise assume args are being passed directly in.
    local origArgs
    if frame == mw.getCurrentFrame() then
        origArgs = frame:getParent().args
        for k, v in pairs(frame.args) do
            origArgs = frame.args
            break
        end
    else
        origArgs = frame
    end
    
    -- Trim whitespace and remove blank arguments for demospace and page parameters.
    local args = {}
    for k, v in pairs(origArgs) do
        if type(v) == 'string' then
            v = mw.text.trim(v) -- Trim whitespace.
        end
        if k == cfg.demospace or k == cfg.page then
            if v ~= '' then
                args[k] = v
            end
        else
            args[k] = v
        end
    end
    
    return p._main(args)
end

return p