local getArgs = require("Module:Arguments").getArgs
local sbl = require("Module:Spam-blacklist")
local p = {}
local sites = {}
local users = {}

local templateArgs = getArgs(mw.getCurrentFrame(), {
	parentOnly = true
})

local searchLink = function(site)
	local args = {
		search = 'insource:"' .. site .. '"', 
		profile = 'advanced',
		fulltext = 1
	}
	local ns = {
		0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
		11, 12, 13, 14, 15, 710, 711,
		828, 829, 2300, 2301, 2302, 2303
	}
	
	for _, v in ipairs(ns) do
		args['ns' .. v] = 1
	end
	
	return tostring(mw.uri.fullUrl('Special:Search', args))
end



for _, args in ipairs(templateArgs) do
	if args:find(">>") then
		local els = mw.text.split(args, ">>", true)
		table.insert(sites, mw.text.trim(els[1]))
		table.insert(users, mw.text.trim(els[2]))
	else
		table.insert(sites, mw.text.trim(args))
		table.insert(users, "__")
	end
end

function p.sites()
	local list = {}
	
	for _, site in ipairs(sites) do
		table.insert(
			list,
			"* " .. mw.getCurrentFrame():expandTemplate({
				title = "Spam/sites",
				args = {
					site:gsub("%.", "\\."):gsub("%/", "\\/")
				}
			})
		)
	end
	
	return table.concat(list, "\n")
end


function p.users()
	local list = {}
	
	for _, user in ipairs(users) do
		if user ~= "__" then
			table.insert(
				list,
				"* " .. mw.getCurrentFrame():expandTemplate({
					title = "Spam/users",
					args = {user}
				})
			)
		else
			table.insert(
				list, tostring(
					mw.html.create("li"):css("visibility", "hidden")
				)
			)
		end
	end
	
	return table.concat(list, "\n")
end

function p.ticks()
	local list = {}
	
	for _, site in ipairs(sites) do
		local li = ' (' ..
			'<span class="plainlinks">' ..
				'[' .. searchLink(site) .. ' tìm kiếm]' ..
			'</span>' ..
		')'
		
		if sbl._isAdded("\\b" .. site:gsub("%.", "\\.") .. "\\b") then
			li = '* '
				.. mw.getCurrentFrame():expandTemplate({ title = 'Tick3' })
				.. ' '
				.. mw.getCurrentFrame():expandTemplate({ title = 'Green', args = {'Đã thêm'} })
				.. li
		else
			li = '* Chưa thêm' .. li
		end
		
		table.insert(list, li)
	end
	
	return table.concat(list, "\n")
end

return p