Module:Merchants

From Sun Haven Wiki
Jump to navigation Jump to search

A dependency of Module:Items which is used in the {{GrowthStages}} template.


Subpages

local p = {} --p stands for package
local frame = mw.getCurrentFrame()

local data = mw.loadData( 'Module:Datatables' )
local utils = require('Module:Utilities')
local strings = require('Module:Strings')

local trim = mw.text.trim

-- [Module] Returns a table of key value pairs representing the requested merchant
-- name = The name of the merchant
function getMerchantByName(name)
	for _, merchant in ipairs(data.merchants) do
		if merchant.name == name then
			return merchant
		end
	end
	return false
end


-- [Module] Returns a table of key value pairs representing the requested merchant
-- name = The name of the item
function p.GetMerchantsByItem(name)
	name = utils.resolveParameter(name)
	
	local m = {}
	for _, merchant in ipairs(data.merchants) do
		for _, item in ipairs(merchant.items) do
			if item.name == name then
				m[#m+1] = merchant
			end
		end
	end
	
	return m or false
end

-- Returns the value of Merchant/Tag, false if it cannot be found
-- tag = Merchant Tag
-- name = Name of the Merchant
function p.GetByName(tag, name)
    name = name or utils.resolveParameter(tag, 2, false)
	tag = utils.resolveParameter(tag)
	
    local merchant = getMerchantByName(name)
    return (merchant and merchant[tag]) or "Unknown"
end

-- Returns a formatted wikitable of merchants selling the specified item
-- name = Name of the Item
function p.GetPurchasedFromTable(name)
	
	local f = name
	name = utils.resolveParameter(f)
	
    merchants = p.GetMerchantsByItem(name)
    
    local header = '{| class="fandom-table sortable" style="text-align:center;"\n! Location !! Value'..nl
    local rows = cstr.empty
    local footer = '|}'

    if #merchants > 0 then
	    for _,merchant in ipairs(merchants) do
			local item = getItem(name, merchant)
	    	rows = rows.."|-"..nl.."|{{il|"..merchant.name.."}}||{{Currency|"..merchant.currency.."|"..item.value.."}}"..nl
	    end
    else
    	rows = "|-"..nl.."|colspan=2|No Merchants sell "..name..nl
    end
    
	return frame:preprocess(header..rows..footer)
end


-- Returns the value of Merchant/Tag, false if it cannot be found
-- tag = Merchant Tag
-- name = Name of the Merchant
function getItem(name, merchant)
	for _, item in ipairs(merchant.items) do
		if item.name == name then
			return item
		end
	end
	
    return false
end

return p