Module:NewsSearch

From TwogPedia
Revision as of 14:24, 13 July 2023 by Couchor (talk | contribs)

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

local getArgs = require('Module:Arguments').getArgs
local cargo = mw.ext.cargo

local NewsSearch = {}

function NewsSearch.main(frame)
	local args = getArgs(frame)
	
	local tableContainer = mw.html.create('div')
	if args.games == nil and args.categories == nil then return tableContainer:wikitext('At least one category or game needs to be chosen') end
	local whereStr = ''

	if args.categories then
		local categories = mw.text.split(args.categories, ',')
		whereStr = whereStr .. '('
		for i = 1, #categories do
			if i ~= 1 then whereStr = whereStr .. ' OR ' end
			whereStr = whereStr .. ' category HOLDS WITHIN "' .. categories[i] .. '"'
		end
		whereStr = whereStr .. ')'
	end
	
	if args.games then
		if args.categories then 
			whereStr = whereStr .. ' AND (' 
		else 
			whereStr = whereStr .. '(' 	
		end
		
		local games = mw.text.split(args.games, ',')
		for i = 1, #games do
			if i ~= 1 then whereStr = whereStr .. ' OR ' end
			whereStr = whereStr .. ' game HOLDS WITHIN "' .. games[i] .. '"'
		end
		whereStr = whereStr .. ')'
	end
	
	whereStr = whereStr

	local tables = 'News'
	local fields = '_pageName, date, category, game'
	local cargoArgs = {
		where = whereStr,
		orderBy = 'date DESC',
		limit = 200
	}
	local results = cargo.query(tables, fields, cargoArgs)

	if #results > 0 then
		for i = 1, #results do
			local result = results[i]
			local dateString = mw.ustring.gsub(result.date, "%s(AM|PM)$", "")

			-- Use os.date to convert the string to a table of date and time components
			local dateTimeTable = os.date("*t", os.time({year=string.sub(dateString, 1, 4), month=string.sub(dateString, 6, 7), day=string.sub(dateString, 9, 10), hour=tonumber(string.sub(dateString, 12, 13)) + ((string.sub(dateString, 22, 22) == "PM") and 12 or 0), min=string.sub(dateString, 15, 16), sec=string.sub(dateString, 18, 19)}))
			
			-- Use os.date again to format the date and time components into a desired format
			local formattedDate = os.date("%d %b %Y %H:%M", os.time(dateTimeTable))

			local news = mw.html.create('div'):wikitext(formattedDate .. ' - [[' .. result._pageName .. ']]')
			tableContainer:node(news)
		end
	else
		return tableContainer:wikitext('No news found with the matching set.') 
	end

	return tableContainer

end

return NewsSearch