Module:GeneralPortSectorSummary

From MicrasWiki
Jump to navigationJump to search

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

local p = {}

local ag = require("Module:AutoUpdateAgPrices")
local manf = require("Module:AutoUpdateManfPrices")
local serv = require("Module:AutoUpdateServPrices")

local function round(num, places)
	local mult = 10 ^ (places or 0)
	return math.floor(num * mult + 0.5) / mult
end

local function fmtPct(num)
	num = round(num, 1)
	if num > 0 then
		return string.format("+%.1f%%", num)
	elseif num < 0 then
		return string.format("%.1f%%", num)
	else
		return "0.0%%"
	end
end

local function colorForPct(pct)
	if pct > 0 then
		return "#d8f0d2", "#1f5f1f"
	elseif pct < 0 then
		return "#f8d7d7", "#8b1e1e"
	else
		return "#f3f3f3", "#555555"
	end
end

local function getSectorData(key)
	if key == "agriculture" or key == "ag" then
		return ag.getAverageData()
	elseif key == "industry" or key == "manufacturing" or key == "manf" then
		return manf.getAverageData()
	elseif key == "services" or key == "serv" then
		return serv.getAverageData()
	end
	return nil
end

local function renderRow(row)
	local bg, fg = colorForPct(row.pctChange)

	return table.concat({
		'|-',
		'| style="text-align:left;" | ' .. row.label,
		string.format(
			'| style="background:%s; color:%s; font-weight:bold;" | %s',
			bg, fg, fmtPct(row.pctChange)
		),
		string.format(
			'| style="background:%s; color:%s;" | Average adjusted (%.4f) vs base (%.4f): %s %s',
			bg, fg, row.avgNew, row.avgBase, row.avgSym, row.avgLevel
		)
	}, "\n")
end

function p.main(frame)
	local sectors = {
		ag.getAverageData(),
		manf.getAverageData(),
		serv.getAverageData()
	}

	local out = {}
	table.insert(out, '{| class="wikitable" style="width:100%; text-align:center;"')
	table.insert(out, '|-')
	table.insert(out, '! Sector !! Average Daily Change !! Summary')

	for _, row in ipairs(sectors) do
		table.insert(out, renderRow(row))
	end

	table.insert(out, '|}')
	return table.concat(out, "\n")
end

function p.row(frame)
	local key = mw.text.trim((frame.args[1] or frame.args.sector or ""):lower())
	local row = getSectorData(key)

	if not row then
		return "No valid sector specified."
	end

	local out = {}
	table.insert(out, '{| class="wikitable" style="width:100%; text-align:center;"')
	table.insert(out, '|-')
	table.insert(out, '! Sector !! Average Daily Change !! Summary')
	table.insert(out, renderRow(row))
	table.insert(out, '|}')

	return table.concat(out, "\n")
end

return p