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, hidename)
	local isip = (isIpOrRange(sock) ~= "")
	local template = isip and "checkip" or "checkuser"
	local li = mw.html.create('li')
	if isip then
		li:attr('class', "template-sock-list-ip")
		li:attr('data-ip', sock)
	else
		li:attr('class', "template-sock-list-user")
		li:attr('data-user', sock)
	end
	li:wikitext(frame:expandTemplate{title=template, args={sock, ['master name']=master, ['hidename']=(hidename and '1' or ''), 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 .. " 用戶互動分析]"
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 .. " 互動時間線]"
end

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

return p