Module:CharacterSkill

From Granblue Fantasy Wiki
Jump to: navigation, search

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

local p = {}

local function stripRefTags(wikitext)
	local w = wikitext:gsub("<ref%s[^>]*/>", "")
	w = w:gsub("<ref[^>]*>.-</ref>", "")
	return w
end

function findArg(needle, haystack)
	local pattern = '|'..needle..'='
	
	local startIndex = haystack:find(pattern, 0, true)
	if startIndex == nil then
		return 'Not Found'
	end
	startIndex = startIndex + pattern:len()
	
	local endIndex = haystack:find('\n|', startIndex, true)
	endIndex = endIndex - 1
	
	local result = haystack:sub(startIndex,endIndex)
	
	return mw.text.trim(result)
end

function splitByLineBreak(text, index)
	index = tonumber(index)
	text = text .. "<br />"   -- Add extra <br/> so we can capture last group

	local matches = {}
	for t in text.gmatch(text, "([^<]*)<br%s?/>") do
	    matches[#matches + 1] = t
	end 
	
	return matches[index]
end

function p.renderSkill(frame)
	mw.log('Module:CharacterSkill: render start: ' .. os.clock())
	local template = frame.args.template
	local characterName = frame.args.characterName
	local skillIndex = frame.args.skillIndex
	local additionalArgs = frame.args.additionalArgs

	mw.log('Module:CharacterSkill: load data for '..characterName..' skill '..skillIndex..': ' .. os.clock())
	local title = mw.title.new(characterName)
	local rawPage = title:getContent()
	
	mw.log('Module:CharacterSkill: find args:' .. os.clock())
	local iconArg = 'a'..skillIndex..'_icon'
	local nameArg = 'a'..skillIndex..'_name'
	local effdescArg = 'a'..skillIndex..'_effdesc'
	local icon = findArg(iconArg, rawPage)
	local name = findArg(nameArg, rawPage)
	name = mw.text.trim(splitByLineBreak(name, 1))         -- Split by linebreak and retrieve first match and trim
	
	local effdesc = findArg(effdescArg, rawPage)

	mw.log('Module:CharacterSkill: expandTemplate')
	local args = {}
	args['link'] = characterName
	args['name'] = name
	args['icon'] = icon
	args['effdesc'] = frame:preprocess(stripRefTags(effdesc))

	-- Pass `frame.args.additionalArgs` to `args`
	if additionalArgs ~= nil then
		for arg in (additionalArgs):gmatch('[^;]+') do
			local i = arg:find('=')
			args[arg:sub(0, i-1)] = arg:sub(i+1)
		end
	end

	mw.log('Module:CharacterSkill: done: ' .. os.clock())
	return frame:expandTemplate{ title = template, args = args }
end

function p.testRender()
	local frame = mw.getCurrentFrame()
	frame.args.template = 'CharacterSkill/Template'
	frame.args.characterName = 'Albert'
	frame.args.skillIndex = '1'
	frame.args.additionalArgs = 'alt=false;skillNo=1;large=false;noicon=false'
	return p.renderSkill(frame)
end

function p.testSplit()
	local text = "foo<br/>bar<br />baz"
	mw.log(1, splitByLineBreak(text, 1))
	mw.log(2, splitByLineBreak(text, 2))
	mw.log(3, splitByLineBreak(text, 3))
	return
end

return p