FANDOM


local utils = require("Module:TemplateUtils")
 
-- Table template parameters:
--1: table classes
--2: table headers
--3: table rows
local tableTemplate = [=[<table class="%s">
<tr>%s</tr>
%s
</table>]=]
 
-- Table header template parameters:
--1: header contents
local headerTemplate= "<th>%s</th>"
 
 
-- Table row template parameters:
--1: cells
local rowTemplate= "<tr>%s</tr>"
 
-- Row cell template parameters:
--1: cell contents
local cellTemplate= "<td>%s</td>"
 
local function Table(classes,headers,rows)
	return string.format(tableTemplate,classes,headers,rows)
end
 
local function Header(s)
	return string.format(headerTemplate,s)
end
 
local function Row(cells)
	return string.format(rowTemplate,cells)
end
 
local function Cell(s)
	return string.format(cellTemplate,s)
end
 
local function Column(header,pattern,...)
	return {header=header,pattern=pattern,...}
end
 
local function GetDataFromPath(data,path)
	if #path == 0 then return data end
	return GetDataFromPath(data[table.remove(path,1)],path)
end
 
local function ProcessArgs(rawargs, currentKey, data)
	local results = {}
	for i = 1, #rawargs do
		local args = mw.text.split(rawargs[i],"%.")
		local context = data[table.remove(args,1)][currentKey]
		context._key = currentKey
		table.insert(results,GetDataFromPath(context,args))
	end
	return unpack(results)
end
 
 
local function trim(s)
  -- from PiL2 20.4
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end
 
local function TableFromData(frame)
	local input = utils.RecreateTable(frame:getParent().args)
	local classes= trim(input.classes)
	local keys = mw.text.split(trim(input.data),",")
	mw.log(classes,unpack(keys))
	local headerString = ""
	local columns = {}
	for i = 1, #input do
		table.insert(columns, Column(unpack(mw.text.split(trim(input[i]),","))))
		mw.log(columns[i].header,columns[i].pattern, unpack(columns[i]))
		headerString = headerString..Header(columns[i].header)
	end
	local data = {}
	for i = 1, #keys do
		local name = "data"..i
		data[name] = {}
		local path = mw.text.split(keys[i],"%.")
		keys[i] = {}
		local rawdata=GetDataFromPath(mw.loadData("Module:"..table.remove(path,1)),path)
		for k,v in pairs(rawdata) do
			local t = utils.RecreateTable(v)
			t._key = k
			data[name][k]=t
			table.insert(keys[i],k)
		end
		table.sort(keys[i])
	end
	local rowKeys = keys[1]
	local rows = {}
	for i = 1, #rowKeys do
		local cells = ""
		for j = 1, #columns do
			cells = cells..Cell(string.format(columns[j].pattern,ProcessArgs(columns[j],rowKeys[i],data)))
		end	
		table.insert(rows,Row(cells))
	end
	return utils.PreProcess(frame,Table(classes,headerString,table.concat(rows)))
end
 
 
return {TableFromData= TableFromData}