local MessageBox = require('Module:Message box')
local Gadgets = require('Module:Gadgets')
local Arguments = require('Module:Arguments')
local TableTools = require('Module:TableTools')

local p = {}

p.main = function(frame)
	local args = Arguments.getArgs(frame)
	return p.core(args.page or mw.title.getCurrentTitle().fullText)
end

p.core = function(page)
	local mfd = ''
	local content = mw.title.new(page).content
	local result = content:match("/%* ({{mfd.-}})")
	if result then
		mfd = mw.getCurrentFrame():preprocess(result)
	end
	local len = page:len()
	if len < 4 then
		-- Too short page name, do nothing
		return mfd
	end
	
	if page:sub(-4, -1) == '.css' then
		local basepage = page:sub(0, -5)
		local sisterpage = basepage..'.js'
		return mfd .. p.makeMessage('css', mw.title.new(basepage), mw.title.new(sisterpage), 'js')
	end
	
	if page:sub(-3, -1) == '.js' then
		local basepage = page:sub(0, -4)
		local sisterpage = basepage..'.css'
		return mfd .. p.makeMessage('js', mw.title.new(basepage), mw.title.new(sisterpage), 'css')
	end
	return mfd
end

local skins = {
	['common'] = true,
	['vector-2022'] = true,
	['vector'] = true,
	['timeless'] = true,
	['minerva'] = true,
	['monobook'] = true,
	['modern'] = true,
	['cologneblue'] = true
}

p.gadget_text = function(name, repo)
	local lang = mw.getContentLanguage()
	local options = repo[name].options
	local dependents = {}
	if options.hidden ~= nil then
		-- Find dependents
		for n, c in pairs(repo) do
			local deps = c.options.dependencies and 
				TableTools.listToSet(mw.text.split(c.options.dependencies, ',', false)) or {}
			local peers = c.options.peers and 
				TableTools.listToSet(mw.text.split(c.options.peers, ',', false)) or {}
			if deps['ext.gadget.'..name] ~= nil or peers[name] ~= nil then 
				table.insert(dependents, '[[Special:Gadgets#gadget-'..n..'|'..n..']]')
			end
		end
	end
	local usage = Gadgets.get_usage(name)
	if usage == -1 then
		usage = "an unknown number of"
	else
		usage = lang:formatNum(usage)
	end
	return 'This page is loaded as a part of the ' ..
		'[[Special:Gadgets#gadget-'..name..'|'..name..']] gadget' ..
		(options.hidden ~= nil and ', a hidden gadget'..
			(#dependents > 0 and ' used by '..mw.text.listToText(dependents)..'.' or '.') or 
		(options.default ~= nil and ', <b>which is enabled by default</b>.' or 
		(', used by '..usage..' users. '))) ..
		'<br>'
end

p.makeMessage = function(pagetype, basepage, sisterpage, sistertype)
	local text = ''
	if basepage.namespace == 2 then
		if skins[basepage.subpageText] ~= nil then
			-- We are on a user skin file
			text = 'The accompanying .'..sistertype..' page for this skin '..
				(sisterpage.exists and 'is' or 'can be added')..' at [['..sisterpage.fullText..']].'
		else
			-- We are on some script page, not a user skin file
			local docpageExists = basepage.exists
			local sisterpageExists = sisterpage.exists
			
			if docpageExists and sisterpageExists then
				text = 'This [[Wikipedia:User scripts|user script]] seems to have a documentation page at [['..basepage.fullText..']] and an accompanying .'..sistertype..' page at [['..sisterpage.fullText..']].'
			elseif docpageExists and not sisterpageExists then
				text = 'This [[Wikipedia:User scripts|user script]] seems to have a documentation page at [['..basepage.fullText..']].'
			elseif sisterpageExists then
				text = 'Documentation for this [[Wikipedia:User scripts|user script]] can be added at [['..basepage.fullText..']]. This user script seems to have an accompanying .'..sistertype..' page at [['..sisterpage.fullText..']]. '
			else 
				text = 'Documentation for this [[Wikipedia:User scripts|user script]] can be added at [['..basepage.fullText..']].'
			end
		end
	
	elseif basepage.namespace == 8 then
		if basepage.text:find('^Gadget-') ~= nil then
			local gadgetRepo = Gadgets.parse()
			local shortName = basepage.text:gsub('^Gadget%-', '') .. '.' .. pagetype
			for name, config in pairs(gadgetRepo) do
				if TableTools.inArray(config.pages, shortName) then
					text = text .. p.gadget_text(name, gadgetRepo)
				end
			end
		end
	end
	
	if text ~= '' then
		return mw.getCurrentFrame():extensionTag{
			name = 'templatestyles', args = { src = 'Module:Script doc auto/styles.css' }
		} .. MessageBox.main('fmbox', {
			class = 'script-doc-auto-box',
			id = 'mw-script-doc',
			type = 'system',
			image = '[[File:Template-info.svg|43x40px]]',
			text = text
		})
	end
	return ''
end

return p