Module:MaroScale

From MTG Wiki
Revision as of 06:00, 27 December 2016 by >Corveroth
Jump to navigation Jump to search

Documentation for this module may be created at Module:MaroScale/doc

-- Little bit of Lua for building tables for the Storm and Rabiah scales.
-- Mechanics have been re-ranked in the past, and it's probably interesting to track their drift.
-- Rather than force editors to track the newest one, let's see if we can't do it in code.

local MaroScale = {}

function MaroScale.TableBuilder(frame)
	local args = frame:getParent().args -- coming from one layer up
	
	-- Imitating navbox, here. I trust they know what they're doing.
	-- Read the arguments in the order they'll be output in, to make references number in the right order.
    local _
    _ = args.type
    _ = args.above
    for i = 1, 200 do
        _ = args["entry" .. tostring(i)]
        _ = args["ratings" .. tostring(i)]
    end
	
	-- Table type
	local type = args.type
	local tbl = mw.html.create("table"):addClass("wikitable"):addClass("sortable")
	tbl:tag("tr")
		:tag("th"):wikitext(type):done()
		:tag("th"):wikitext("Latest ranking"):done()
		:tag("th"):wikitext("History of rankings"):done()

	
	-- Seriously this loop is entirely too clever
	local listnums = {}
	for k, v in pairs(args) do
        local listnum = ('' .. k):match('^ratings(%d+)$')
        if listnum then table.insert(listnums, tonumber(listnum)) end
    end
    table.sort(listnums)
	
	for i, listnum in ipairs(listnums) do
		local newestDate, newestRating = 0, 0
		local rating, refDate, refString, t
		local ratings = {}
		string.gsub(args["ratings"..listnum], "{(.-)}", function(a)
			rating, refDate, refString = string.match(a, "(%d+),([%d%-]+),(.+)")
			rating = tonumber(rating)
			
			-- Dates MUST be yyyy-mm-dd
			t = os.time({year=string.sub(refDate, 1,4), month=string.sub(refDate, 6,7), day=string.sub(refDate, 9,10),})
			if t > newestDate then
				newestDate = t
				newestRating = rating
			end
			
			table.insert(ratings, {rating = rating, refDate = refDate, refString = refString, t = t})
		end)
		
		-- maybe later, it's not worth the effort right now
		table.sort(ratings, function(a,b) return a.t < b.t end)
		
		local entryLink = "[["..args["entry"..listnum].."]]"
		
		local row = tbl:tag("tr")
		row:tag("td"):wikitext(entryLink or "Name not given")
		row:tag("td"):wikitext(newestRating or "Rating not found")
		local cell = row:tag("td"):addClass("hlist")
		local list = cell:tag("ul"):cssTest("list-style-type: none !important;")

		for n, rating in pairs(ratings) do
			if n ~= #ratings then
				list:tag("li"):wikitext(rating.rating .. rating.refString .. ", ")
			else
				list:tag("li"):wikitext(rating.rating .. rating.refString)
			end
		end

	end
	return tbl
end

return MaroScale