Module:Asof

From The Satanic Wiki
Jump to navigation Jump to search

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

-- <pre> Creates dated statements
local p = {}
local u = require("Module:Utility")
local tValidMonths = {
	january = 1,
	february = 2,
	march = 3,
	april = 4,
	may = 5,
	june = 6,
	july = 7,
	august = 8,
	september = 9,
	october = 10,
	november = 11,
	december = 12,
}

--% Entry point Creates a dated statement and categorizes the page
--@ frame (table) A scribunto frame
--: (string) A string containing "As of", and a category with the date
function p.main(frame)
	local tArgs = u.getArgs(frame)
	local sYear = tonumber(tArgs[1])
	local sMonth = string.lower(tArgs[2] or "")
	local sDay = tonumber(tArgs[3])
	local lc = tArgs.lc
	local nocat = tArgs.nocat
	local prefix = lc and "as of " or "As of "
	local lang = mw.language.new("en")
	local sFormat = "Y"
	local isYear, isMonth, isDay = p.isValidDate(sYear, sMonth, sDay)
	
	if not isYear then 
		return error("Invalid date, year `" .. tostring(tArgs[1]) .. "` is wrong.")
	end
	
	if isMonth then
		sMonth = tonumber(sMonth) or tValidMonths[sMonth]
		sFormat = "F " .. sFormat
		if isDay then 
			sFormat = "d " .. sFormat
		else
			sDay = os.date("%d")
		end
	else 
		sDay = sDay or os.date("%d") 
		sMonth = os.date("%m")
	end
	
	local sDefOutput = prefix .. lang:formatDate(sFormat, sYear .. "/" .. sMonth .. "/" .. sDay)
	local sOutput = tArgs.alt or sDefOutput 
	
	if not nocat then
		sOutput = sOutput .. " [[Category:Dated statements from " .. sYear .. "]]"
	end
	
	return sOutput
end

--% Checks if the date is valid
--@ year (string) The required year
--@ month (string) The required month 
--@ day (string) The required day
--: (boolean) True if valid year
--: (boolean) True if valid month
--: (boolean) True if valid day
function p.isValidDate(year, month, day)
	local tValidDays = {31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30}
	local bYear, bMonth, bDay
	
	month = tonumber(month) or string.lower(month)
	month = tonumber(month) or tValidMonths[month]
	mw.log(year)
	if tonumber(year) and tonumber(year) > -1 then
		if year % 4 == 0 and not (year % 100 == 0 and year % 400 > 0) then
			tValidDays[2] = 29
		end
		bYear = true
	end
	if tValidMonths[month] or tValidDays[month] then
		bMonth = true
		if tonumber(month) and tonumber(day) and
			0 < day and tValidDays[month] >= tonumber(day) then
			bDay = true
		end
	end
	return bYear, bMonth, bDay
end
-- end date functions

return p