Module:PriceCalculator

From HighSpell Wiki
Revision as of 12:43, 26 June 2025 by Ryan (talk | contribs)
Jump to navigation Jump to search

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

local p = {}

-- Internal function to calculate price
function p._calculate(price, priceType)
	-- Sanitize input: convert to string, remove commas
	price = tostring(price):gsub(",", "")
	price = tonumber(price)

	-- Error handling
	if not price or price < 0 then
		return "Invalid price: " .. tostring(price)
	end

	-- Lookup conversion factors
	local percent = {
		sell = 0.375,
		minor = 0.250125,
		major = 0.375
	}

	local factor = percent[priceType]
	if not factor then
		return "Invalid type: " .. tostring(priceType)
	end

	-- Calculate and return rounded result
	return math.floor(price * factor + 0.0)
end

-- Entry point for #invoke
function p.calculate(frame)
	local args = frame.args -- Use direct args from #invoke
	local price = args.price or args[1]
	local priceType = args.type or args[2]
	return p._calculate(price, priceType)
end

function p.renderPrice(frame)
	local args = frame.args
	local inputPrice = args.price or args[1] or "1"
	local priceType = args.type or args[2] or "sell"
	local min = tonumber(args.min or args.MinimumQuantity or "1") or 1
	local max = tonumber(args.max or args.MaximumQuantity or "") -- optional

	-- Calculate actual price using your _calculate function
	local price = tonumber(p._calculate(inputPrice, priceType))
	if not price then
		return "Error: invalid calculated price"
	end

	-- Helper to format numbers
	local function format(num)
		return mw.getContentLanguage():formatNum(num)
	end

	-- Coin icon HTML (customize as needed)
	local coinIcon = '[[File:Coins.png|22px|link=Coins]]'

	-- Logic for display
	if max and max ~= min then
		if price > 1 then
			return string.format(
				'<abbr title="%d coins each">%s–%s</abbr>%s',
				price,
				format(price * min),
				format(price * max),
				coinIcon
			)
		else
			return string.format('%s–%s%s', format(price * min), format(price * max), coinIcon)
		end
	elseif min == 1 then
		return string.format('%s%s', format(price), coinIcon)
	else
		if price > 1 then
			return string.format(
				'<abbr title="%d coins each">%s</abbr>%s',
				price,
				format(price * min),
				coinIcon
			)
		else
			return string.format('%s%s', format(price * min), coinIcon)
		end
	end
end


return p