Module:Calculator/AgilityObstacle

Revision as of 21:13, 23 April 2024 by Ricewind (talk | contribs) (Make costReduction parsing more robust)

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

local p = {}

local yesno = require('Module:Shared/Yesno')
local Num = require('Module:Number')
local Constants = require('Module:Constants')
local Agility = require('Module:Skills/Agility')
local Shared = require('Module:Shared')
local Icons = require('Module:Icons')
local Debug = require('Module:Debug') -- Comment out when Module is finalised.

local function getItemIcon(itemName, amount)
	if itemName == 'GP' then
		return Icons.GP(amount)
	end
	
	if itemName == 'SC' then
		return Icons.SC(amount)
	end
	
	return Icons.Icon({itemName, type='item', qty = amount, notext=true})
end

-- Gets all associated metadata from an obstacle based on its name.
local function getObstacle(name, costReduction)
	name = Shared.specialTitleCase(name)
	local obstacle = Agility.getObstacle(name) or Agility.getPillar(name)
	if obstacle == nil then
		error("Unknown Agility obstacle or pillar name: " .. name)
	end

	-- Resolve obstacle slot.
	local slot = 0
	if string.find(name, 'Pillar') then
		if string.find(name, 'Elite') then
			slot = 'Elite Pillar'
		else
			slot = 'Pillar'
		end
	else
		slot = obstacle.category + 1
	end
	
	-- Apply cost reduction, if available.
	local itemCosts = Agility.getObstacleCosts(obstacle)
	if costReduction then 
		Agility.applyCostReduction(itemCosts, costReduction) 
	end
	
	local obstacleInfo = {
		Name = obstacle.name,
		Slot = slot,
		Obstacle = obstacle,
		LevelRequirements = Agility.getObstacleRequirements(obstacle),
		ItemCosts = itemCosts,
	}

	return obstacleInfo
end

local function getObstacles(obstacleNames, checkDoubleSlots, costReduction)
	-- Collect all obstacles and filter out nill values.
	local courseObstacles = {}
	local courseSlots = {}
	
	for _, v in pairs(obstacleNames) do
		local currObstacle = getObstacle(v, costReduction)
		if currObstacle then
			if checkDoubleSlots and courseSlots[currObstacle.Slot] == true then
				error('There are two or more obstacles in the same slot. Obstacle: ' .. currObstacle.Name .. ' Slot: ' .. currObstacle.Slot)
			end
			
			courseSlots[currObstacle.Slot] = true
			table.insert(courseObstacles, currObstacle) 
		end
	end
	
	return courseObstacles
end

function p.calculateCourse(obstacleNames, checkDoubleSlots, costReduction)
	local funcPoolCosts = function(tbl, item, amount)
		Shared.addOrUpdate(tbl, item, function(x) x = x or 0 return x + amount end)
	end
	
	local courseObstacles = getObstacles(obstacleNames, checkDoubleSlots, costReduction)

	-- Calculate the highest level requirements and the total amount of items
	-- required to build this agility course.
	local courseLevelRequirements = {}
	local courseItemCosts = {
		['Items'] = {}
	}
	
	for _, obstacle in pairs(courseObstacles) do
		-- Pool together highest level requirements for the entire course.
		for skill, level in pairs(obstacle.LevelRequirements) do
				Shared.addOrUpdate(courseLevelRequirements, skill, 
					function(x)	
						if x then return math.max(x, level)	else return level end 
					end)
		end
		
		-- Pool together total item costs to build the entire course course.
		local obstacleCosts = obstacle.ItemCosts
		if obstacleCosts['GP'] then funcPoolCosts(courseItemCosts, 'GP', obstacleCosts['GP']) end
		if obstacleCosts['SC'] then funcPoolCosts(courseItemCosts, 'SC', obstacleCosts['SC']) end
		
		for item, amount in pairs(obstacleCosts['Items']) do
			funcPoolCosts(courseItemCosts['Items'], item, amount)
		end
	end

	-- Sort course on category
	local sortFunc = function(a, b)
		-- Special case to sort pillars AFTER all regular obstacles.
    	local pillar = { ["Pillar"] = 99, ["Elite Pillar"] = 100 }
		return (pillar[a.Slot] or a.Slot) < (pillar[b.Slot] or b.Slot)
	end
	
	table.sort(courseObstacles, sortFunc)
	
	return {
		Obstacles = courseObstacles,
		CourseLevelRequirements = courseLevelRequirements,
		CourseItemCosts = courseItemCosts
	}
end

-- Stupid shenanigans to filter out numeric parameters.
-- Because just iterating over #args doesn't work for some reason...
function parseObstacleArgs(args)
	local obstacleNames = {}
	for k, v in pairs(args) do
		k = tonumber(k)
		if k then 
			table.insert(obstacleNames, v:match("^%s*(.-)%s*$")) 
		end
	end
	
	return obstacleNames
end

function p.getCourseList(frame)
	local args = frame:getParent().args
	return p._getCourseList(args)
end

function p._getCourseList(args)
	-- Parse optional parameters
	local costReduction = {
		['GP']   = Num.toNumberOrDefault(args['gpCostReduction'], 0),
		['SC']   = Num.toNumberOrDefault(args['scCostReduction'], 0),
		['Item'] = Num.toNumberOrDefault(args['itemCostReduction'], 0),
	}
	
	local obstacleNames = parseObstacleArgs(args)
	local courseRequirements = p.calculateCourse(obstacleNames, true, costReduction)
	
	local html = mw.html.create()
    local div = html:tag('div')
    
    if yesno(args['includeObstacles'], true) == true then
		div:tag('b'):wikitext('Obstacles')
		local tbl = mw.html.create("table")
        	:addClass("wikitable stickyHeader text-align-left")
        	
        tbl	:tag("tr")
        		:tag("th"):wikitext("Slot")
        		:tag("th"):wikitext("Obstacle")

		for _, v in pairs(courseRequirements.Obstacles) do
			tbl	:tag('tr')
					:tag('td')
						:css('text-align', 'right')
						:wikitext(v.Slot)
					:tag('td')
						:wikitext(Icons.Icon({v.Name, type='agility'}))
		end
		
		div:node(tbl)
		div:wikitext('<br>')
    end

    if yesno(args['includeitems'], true) then
    	div:tag('b'):wikitext('Items Required')
    	local ul = div:tag('ul')
    	
    	local courseItems = courseRequirements.CourseItemCosts
    	-- Put GP and SC at the top, and remove them from the list
    	-- to avoid sorting and re-adding them below.
    	if courseItems['GP'] then ul:tag('li'):wikitext(getItemIcon('GP', courseItems['GP'])) end
    	if courseItems['SC'] then ul:tag('li'):wikitext(getItemIcon('SC', courseItems['SC'])) end

    	local itemList = Shared.sortDictionary(courseItems['Items'], 
    		function(a, b) return a.item < b.item end,
    		function(a, b) return {item = a, amount = b} end)

		for _, v in pairs(itemList) do
    		ul:tag('li'):wikitext(getItemIcon(v.item, v.amount))
		end
		div:wikitext('<br>')
    end
	
	if yesno(args['includeskills'], true) then
		div:tag('b'):wikitext('Skills Required')
    	local ul2 = div:tag('ul')
    	
    	local skillList = Shared.sortDictionary(courseRequirements.CourseLevelRequirements, 
    		function(a, b) return a.skill < b.skill end,
    		function(a, b) return {skill = a, level = b} end)
    	
    	for _, v in pairs(skillList) do
    		ul2:tag('li'):wikitext(Icons._SkillReq(v.skill, v.level))
    	end
    	div:wikitext('<br>')
	end
	
    return tostring(html)
end

function p.getCourseTable(frame)
	local args = frame:getParent().args
	return p._getCourseTable(args)
end

function p._getCourseTable(args)
	--== Local Functions for formatting Obstacle MetaData ==--
	local function getBonusses(obstacle)
		local bonuses = {}
		for bonusName, bonusValue in pairs(obstacle.modifiers) do
			table.insert(bonuses, Constants._getModifierText(bonusName, bonusValue))
		end
		if Shared.tableIsEmpty(bonuses) then
			table.insert(bonuses, '<span style="color:red">None :(</span>')
		end
		return table.concat(bonuses, '<br/>')
	end
	
	local function getRequirements(requirementsTable)
		local skillList = Shared.sortDictionary(requirementsTable, 
			function(a, b) return a.skill < b.skill end,
			function(a, b) return {skill = a, level = b} end)
		
		local res = {}
		for _, v in pairs(skillList) do
			table.insert(res, Icons._SkillReq(v.skill, v.level))
		end
		return table.concat(res, '<br/>')
	end
	
	local function getCosts(costsTable)
		local res = {}
		    	
		-- Order table with GP, SC first, then the other items.
    	if costsTable['GP'] then table.insert(res, getItemIcon('GP', costsTable['GP'])) end
    	if costsTable['SC'] then table.insert(res, getItemIcon('SC', costsTable['SC'])) end

    	local sortedCosts = Shared.sortDictionary(costsTable['Items'], 
			function(a, b) return a.item < b.item end,
			function(a, b) return {item = a, amount = b} end)

    	for _, v in pairs(sortedCosts) do
    		table.insert(res, getItemIcon(v.item, v.amount))
    	end
		return table.concat(res, '<br/>')
	end
	
	local function getTotalBonuses(obstacles)
		local bonuses = {}
		for _, obstacle in pairs(obstacles) do
			for bonusName, bonusValue in pairs(obstacle.Obstacle.modifiers) do
				table.insert(bonuses, {name = bonusName, value = bonusValue})
			end
		end

		table.sort(bonuses, function(a, b) return a.name < b.name end)
		
		local ret = {}
		for _, bonus in pairs(bonuses) do
			table.insert(ret, Constants._getModifierText(bonus.name, bonus.value))
		end
		if Shared.tableIsEmpty(ret) then
			table.insert(ret, '<span style="color:red">None :(</span>')
		end
		
		return table.concat(ret, '<br/>')
	end

	--== Parse optional parameters==--
	local showTotals = yesno(args['showtotals'], true)
	local obstacleMastery = yesno(args['obstacleMastery'], false)
	
	local costReduction = {
		['GP']   = Num.toNumberOrDefault(args['gpCostReduction'], 0),
		['SC']   = Num.toNumberOrDefault(args['scCostReduction'], 0),
		['Item'] = Num.toNumberOrDefault(args['itemCostReduction'], 0),
	}
	
	local obstacleNames = parseObstacleArgs(args)
	local courseRequirements = p.calculateCourse(obstacleNames, true, costReduction)

	--== Start of table formatting ==--
	local tbl = mw.html.create("table")
       	:addClass("wikitable stickyHeader")
       	
    tbl :tag('tr')
			:tag('th'):wikitext('Slot')
			:tag('th'):wikitext('Obstacle')
			:tag('th'):wikitext('Bonuses')
			:tag('th'):wikitext('Requirements')
			:tag('th'):wikitext('Costs')

	for _, obstacle in pairs(courseRequirements.Obstacles) do
		tbl :tag('tr')
				:tag('td')
					:css('text-align', 'right')
					:wikitext(obstacle.Slot)
				:tag('td'):wikitext(Icons.Icon({obstacle.Name, type='agility'}))
				:tag('td'):wikitext(getBonusses(obstacle.Obstacle))
				:tag('td'):wikitext(getRequirements(obstacle.LevelRequirements))
				:tag('td'):wikitext(getCosts(obstacle.ItemCosts))
	end
	
	if showTotals == true then
		tbl :tag('tr')
				:tag('th')
					:attr('colspan', 2)
					:wikitext('Totals')
				:tag('td')
					:wikitext(getTotalBonuses(courseRequirements.Obstacles))
				:tag('td')
					:wikitext(getRequirements(courseRequirements.CourseLevelRequirements))
				:tag('td')
					:wikitext(getCosts(courseRequirements.CourseItemCosts))
	end

	return tostring(tbl)
end

function p.test()
	local obstacles = {"Rope Climb","Monkey Bars"," Balance Seesaw","Elite Pillar of Conflict"}
	local obs = p.calculateCourse(obstacles)


	Debug.log(obs.CourseItemCosts)
end
return p