Module:Offering

From Coral Island Wiki
Jump to navigation Jump to search

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

local p = {}
local lib = require('Module:Feature')
local Icon = require('Module:Icon')._main
local category = mw.html.create()

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		parentFirst = true,
		removeBlanks = false,
		wrapper = { 'Template:Offering' }
	})
	return p._main(args)
end

function p._main(args)
	local _table = mw.html.create('table'):addClass('article-table fandom-table tdc2 tdc1 thc1 thc2 thc3 thc4 tdbg1')
	local options = {
		delim = args.delim or ';',
		amount_delim = args.amount_delim or '*',
		quality_delim = args.quality_delim or '/',
	}
	
	--headers
	local tr = _table:tag('tr')
	tr:tag('th'):wikitext('Offering')
	tr:tag('th'):wikitext('No of items')
	tr:tag('th'):wikitext('Possible items')
	tr:tag('th'):wikitext('Rewards')
	
	local i = '1'
	while args[i .. '_name'] do
		local tr = _table:tag('tr'):attr('id', args[i .. '_name'])
		tr:tag('td'):wikitext('[[File:', args[i .. '_name'], ' Offering.png|60px|link=]]<br />', args[i .. '_name'])
		tr:tag('td'):wikitext(args[i .. '_amount'] or '5')
		options.str = args[i .. '_items']
		tr:tag('td'):node(p.parseItems(options, 2, 'Offering needs'))
		options.str = args[i .. '_reward']
		tr:tag('td'):node(p.parseItems(options, false, 'Offering rewards'))
		i = tostring(tonumber(i)+1)
	end
	_table:node(require('Module:Namespace detect').main{main=category})
	return _table
end

function p.checkQuality(entry, notePattern)
	if notePattern then
		item, quality = entry:match(notePattern)
		if item == nil then -- will be nil if note is not present
			return entry
		end
		return item, quality
	end
	return entry
end

function p.parseItems(data, columns, catPrefix)
	if not tostring(data.str) then return '' end
	local itemDelim = data.delim
	local countDelim = data.amount_delim
	local qualityDelim = data.quality_delim
	
	-- put all text after the first qualityDelim into the second capture
	local qualityPattern
	if lib.isNotEmpty(qualityDelim) then
		qualityPattern = '^(.-)' .. qualityDelim .. '(.*)$'
	end
	
	local items = mw.html.create():tag('div')
	if tonumber(columns) ~= nil then
		items:addClass('columntemplate'):css{ ['-moz-column-count'] = columns, ['-webkit-column-count'] = columns, ['column-count'] = columns }
	end
	-- mw.logObject(data) -- debug
	for i, entry in ipairs(lib.split(data.str, itemDelim, {noTrim=true})) do
		if not lib.isEmpty(entry) then
			local item, quality = p.checkQuality(entry, qualityPattern) --check for item quality
			local item_parts = lib.split(item, countDelim) --check for item amount
			local name = item_parts[1]
			local amount = item_parts[2] or '1'
			items:node(Icon{
				name = name,
				amount = amount or 1,
				q = quality or '0'
			})
			if catPrefix then
				category:wikitext('[[Category:', catPrefix, ' ', string.lower(name) ,']]')
			end
		end
	end
	return items
end

return p