-- This module implements {{Old move}}.

local p = {}

local messageBox = require('Module:Message box')
local yesno = require('Module:Yesno')
local dateModule = require('Module:Date')._Date
local listModule = require('Module:List').horizontal

-- Create variable used in other functions
local pageType
if (mw.title.getCurrentTitle():inNamespace(1)) then
	pageType = "article"
else
	pageType = "page"
end

-- Build the HTML for collapsing lists
local function makeTable(list, text)
	local collapseTable = mw.html.create("table")
	collapseTable
		:attr({
			class = "mw-collapsible mw-collapsed",
			cellspacing = 0,
			cellpadding = 0
		})
		:css({
			width = "100%",
			background = "transparent",
			margin = 0,
			padding = "0.5em 0 0"
		})
		:tag("tr"):tag("th"):wikitext(text):cssText("text-align: left")
		:tag("tr"):tag("td"):wikitext(mw.ustring.format("\n%s", list))
	return collapseTable
end

local function singleText(args)
	local date = args["date"] or args["date1"] or ""
	local from = args["from"] or args["from1"] or ""
	local to = args["destination"] or args["destination1"] or args["to1"] or args["to"] or ""
	local result = args["result"] or args["result1"] or ""
	local link = args["link"] or args["link1"] or ""
	local dateformat = args["dateformat"] or "dmy"
	local text = ""
	if (date ~= "") then
		if dateModule(date) then
			date = dateModule(date):text(dateformat)
		end
		text = mw.ustring.format("On %s, it was proposed that this %s be [[Wikipedia:Requested moves|moved]]", date, pageType)
	else
		text = mw.ustring.format("It has previously been proposed that this %s be [[Wikipedia:Requested moves|moved]]", pageType)
	end
	if (from ~= "") then
		text = mw.ustring.format("%s from [%s %s]", text, tostring(mw.uri.fullUrl(from, {redirect = "no"} )), from)
	end
	if (to ~= "") then
		text = mw.ustring.format("%s to [[%s]]", text, to)
	end
	text = mw.ustring.format("%s.", text)
	if (result ~= "") then
		if (link ~= "") then
			text = mw.ustring.format("%s The result of [[%s|the discussion]] was '''%s'''.", text, link, result)
		else
			text = mw.ustring.format("%s The result of the discussion was '''%s'''.", text, result)
		end
	elseif (link ~= "") then
		text = mw.ustring.format("%s See [[%s|discussion]].", text, link)
	end
	return text
end

local function row(args, i)
	local date = args["date" .. i] or ""
	local from = args["from" .. i] or ""
	local dateformat = args["dateformat"] or "dmy"
	local to = args["destination" .. i] or args["to" .. i] or ""
	local result = mw.language.getContentLanguage():ucfirst(args["result" .. i]) or ""
	local link = args["link" .. i] or ""
	local rowText = mw.ustring.format("\n*'''%s'''", result)
	if (date ~= "") then
		if dateModule(date) then
			date = dateModule(date):text(dateformat)
		end
		rowText = mw.ustring.format("%s, %s", rowText, date)
	end
	if (from ~= "") then
		rowText = mw.ustring.format("%s, from [%s %s]", rowText, tostring(mw.uri.fullUrl(from, {redirect = "no"} )), from)
		if (to ~= "") then
			rowText = mw.ustring.format("%s to [[%s]]", rowText, to)
		end
	elseif (to ~= "") then
		rowText = mw.ustring.format("%s, to [[%s]]", rowText, to)
	end
	if (link ~= "") then
		rowText = mw.ustring.format("%s, see [[%s|discussion]]", rowText, link)
	end
	rowText = rowText .. "."
	return rowText
end

local function list(args)
	local text = ""
	if (args["result1"]) then -- Support to1 and to in case of multiple rows
		text = mw.ustring.format("%s%s", text, row(args, 1))
	else
		text = mw.ustring.format("%s%s", text, row(args, ""))
	end
	local i = 2
	while (args["result" .. i]) do
		text = mw.ustring.format("%s%s", text, row(args, i))
		i = i + 1 -- Check if to(i+1) exist
	end
	return text
end
	
local function manualList(args)
	local manualListText = ""
	if (args["list"]) then
		if (args["result"] or args["result1"]) then
			manualListText = mw.ustring.format("%s\n'''Other discussions: '''\n%s", manualListText, args["list"])
		else
			manualListText = mw.ustring.format("%s\n%s", manualListText, args["list"])
		end
	end
	if (args["oldlist"]) then
		if (yesno(args["collapse"]) or yesno(args["collapsed"])) then
			manualListText = mw.ustring.format("%s\n'''Older discussions: '''\n%s", manualListText, tostring(args["oldlist"]))
		else
			manualListText = mw.ustring.format("%s\n%s", manualListText, tostring(makeTable(args["oldlist"], "Older discussions:")))
		end
	end
	return manualListText
end

local function showLogs(args)
	local logList, i = {}, 1
	while (args["title" .. i]) do
		local query = mw.uri.buildQueryString({
			["page"] = args["title" .. i],
			["type"] = "move"
		})
		if (i == 1) then -- Hacky way to make the hlist go after "move logs"
			table.insert(logList, mw.ustring.format("\n'''Move logs: '''[%s %s]", tostring(mw.uri.canonicalUrl("Special:Log", query)), args["title" .. i]))
		else
			table.insert(logList, mw.ustring.format("[%s %s]", tostring(mw.uri.canonicalUrl("Special:Log", query)), args["title" .. i]))
		end
		i = i + 1
	end
	logList["style"] = "padding-top: 0.5em;"
	return listModule(logList)
end

local function evaluate(args)
	local text = ""
	local is_collapsed = yesno(args["collapse"]) or yesno(args["collapsed"])
	local has_log_args = args["title"] or args["title1"]
	local has_manual_list = args["list"] or args["oldlist"]
	local has_multiple_rows = args["result1"]
	
	if (has_log_args) then
		text = mw.ustring.format("%s%s", text, showLogs(args))
	end
	
	if (not is_collapsed or has_log_args) then
		-- if the template is collapsed and there are no log arguments,
		-- then we already have "Discussions:" in bold text in bannerText(),
		-- so we don't need to repeat it here
		text = mw.ustring.format("%s\n'''Discussions: '''\n", text)
	end
	
	-- This makes sure we don't show the single version when there's a log or manual list
	if (args["result"]) then
		if (has_log_args or has_manual_list or args["result2"]) then
			text = mw.ustring.format("%s%s", text, list(args))
		else
			text = singleText(args)
		end
	end
	if (has_multiple_rows) then
		text = mw.ustring.format("%s%s", text, list(args))
	end
	if (has_manual_list) then
		text = mw.ustring.format("%s%s", text, manualList(args))
	end
	if (not args["result"] and not has_multiple_rows and not has_manual_list and not has_log_args) then
		return ""
	end

	return text
end

local function bannerText(args)
	local blurb = mw.ustring.format("This %s has previously been nominated to be moved." ..
		" Please review the prior discussions if you are considering re-nomination.", pageType)
	local list = ""

	if (yesno(args["collapse"]) or yesno(args["collapsed"])) then
		if (args["title"] or args["title1"]) then
			list = mw.ustring.format("%s%s", blurb, tostring(makeTable(evaluate(args), "Logs and discussions:")))
		else
			list = mw.ustring.format("%s%s", blurb, tostring(makeTable(evaluate(args), "Discussions:")))
		end
	else
		list = evaluate(args)

		if (mw.ustring.find(list, "proposed that this") == nil) then
			list = mw.ustring.format("%s%s", blurb, evaluate(args))
		end
	end
	
	return list
end

local function renderBanner(args)
	return messageBox.main('tmbox', {
		small = yesno(args["small"]),
		type = 'move',
		text = bannerText(args)
	})
end

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame)
	return renderBanner(args)
end

return p