Fandom Developers Wiki
Documentation icon Module documentation



-- <pre> Creates dated statements
local p = {}
local u = require("Dev:Utility")
local i18n = require("Dev:I18n").loadMessages("Asof")
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 "prefix-lc" or "prefix"
	local lang = mw.language.new(i18n:getLang())
	local sFormat = i18n:msg("format-year")
	local isYear, isMonth, isDay = p.isValidDate(sYear, sMonth, sDay)
	
	if not isYear then 
		return error(i18n:msg("error", tostring(tArgs[1])))
	end
	
	if isMonth then
		sMonth = tonumber(sMonth) or tValidMonths[sMonth]
		sFormat = i18n:msg("format-month")
		if isDay then 
			sFormat = i18n:msg("format-day")
		else
			sDay = os.date("%d")
		end
	else 
		sDay = sDay or os.date("%d") 
		sMonth = os.date("%m")
	end
	
	local sDefOutput = i18n:msg(prefix, lang:formatDate(sFormat, sYear .. "/" .. sMonth .. "/" .. sDay))
	local sOutput = tArgs.alt or sDefOutput 
	
	if not nocat then
		sOutput = sOutput .. "[[Category:" .. i18n:msg("category", 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