Module:Timebomb

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

require('Module:No globals')
local getArgs = require('Module:Arguments').getArgs
local lang = mw.language.new('en')
local frame = mw.getCurrentFrame()

local p = { }

local function trim(str)
	if str then
		return str:gsub("^%s*", ""):gsub("%s*$", "")
	else
		return nil
	end
end

local function length(timebomb, compiled)
	local ts1 = lang:formatDate('U', timebomb)
	local ts2 = lang:formatDate('U', compiled)
	
	return ts1 - ts2
end

local function fixed(timebomb, compiled)
	local length = length(timebomb, compiled)
	local clean = frame:callParserFunction('#dateformat:' .. timebomb)
	
	if length < 0 and compiled then
		error('timebomb date is earlier than the compilation date')
	end

	if compiled then
		local msg = mw.message.new('timebomb fixed')
		msg:params(clean, lang:formatDuration(length, {'days'}))
		return msg:plain()
	else
		return clean
	end
end

local function dynamic(timebomb)
	local length = length(timebomb, 'now')
	local msg = mw.message.new('timebomb dynamic')
	msg:params(lang:formatDuration(length, {'days'}))
	return msg:plain()
end

function p.main(frame)
	local args = getArgs(frame)
	local expiry = trim(frame.args[1] or args.timebomb)
	
	if not expiry or expiry:len() == 0 then
		return ""
	end
	
	if expiry:byte() == 43 then
		return dynamic(expiry)
	else
		return fixed(expiry, args.compiled)
	end
end

return p