local p = {}
local getArgs = require('Module:Arguments').getArgs
local isIpOrRange = require('Module:IPAddress')._isIpOrRange
local yesno = require('Module:Yesno')

function p.main(frame)
	local args = getArgs(frame)
	return p._main(frame, args)
end

function listEntry(frame, sock, master)
	local template = (isIpOrRange(sock) ~= "") and "checkip" or "checkuser"
	local li = mw.html.create('li')
	li:wikitext(frame:expandTemplate{title=template, args={sock, ['master name']=master, bullet='no'}})
	return li
end

function toolEIA(args)
	local url = "https://tools.wmflabs.org/sigma/editorinteract.py?server=zhwiki&users="
		.. mw.uri.encode(args.master)
	for i, sock in ipairs(args) do
		url = url .. "&users=" .. mw.uri.encode(sock)
	end
	return "[" .. url .. " Editor interaction utility]"
end

function toolTimeline(args)
	local user2 = args[1] or ""
	if args.master == user2 then
		user2 = args[2] or ""
	end
	local url = "https://tools.wmflabs.org/interaction-timeline?wiki=zhwiki&user="
		.. mw.uri.encode(args.master) .. "&user=" .. mw.uri.encode(user2)
	return "[" .. url .. " Interaction Timeline]"
end

function p._main(frame, args)
	local lists = mw.html.create('div')
	local socklist = mw.html.create('ul')
	if args[1] then
		for i, sock in ipairs(args) do
			socklist:node(listEntry(frame, sock, args.master))
		end
	end
	lists:node(socklist)
	if yesno(args.tools_link) then
		local toolslist = mw.html.create('dl')
		local tools = mw.html.create('dd')
		tools
			:attr('class', 'plainlinks')
			:wikitext("<b>工具</b>:")
			:node(toolEIA(args))
			:wikitext(" • ")
			:node(toolTimeline(args))
		toolslist:node(tools)
		lists:node(toolslist)
	end
	return lists
end

return p