Módulo:Infobox criar

De RuneScape Wiki
Ir para: navegação, pesquisa
Documentação do módulo
Esta documentação é transcluída de Predefinição:Sem documentação/doc. [editar] [atualizar]
Este módulo não possui nenhuma documentação. Por favor, considere adicionar uma documentação em Módulo:Infobox criar/doc. [editar]
Módulo:Infobox criar's a função main é invocada por Predefinição:Infobox criar.

--<nowiki>

--[=[<pre>
-- Implementa [[Predefinição:Infobox criar]]
--]=]

local p = {}

local yesno = require('Module:Yesno')
local params = require('Module:Paramtest')
local commas = require('Module:Addcommas')
local geprice = require('Module:Mercado')._price
local skillpic = require('Module:Skill clickpic')._main
local mapicons = require('Module:Map_clickpic')
local editbutton = require('Module:Edit button')
local onmain = require('Module:Mainonly').on_main

-- Name mapping for special (multiple choice) items
local specmats = {
	['Arenito'] = { ['Arenito (1 kg)'] = 1, ['Arenito (2 kg)'] = 1, ['Arenito (5 kg)'] = 1, ['Arenito (10 kg)'] = 1 },
	['Energia divina'] = { ['Energia pálida'] = 2000, ['Energia cintilante'] = 1000, ['Energia resplandecente'] = 900, ['Energia luminescente'] = 850, ['Energia faiscante'] = 800,
		['Energia reluzente'] = 700, ['Energia lampejante'] = 650, ['Energia lustrosa'] = 600, ['Energia anciã'] = 500, ['Energia brilhante'] = 450, ['Energia radiante'] = 400,
		['Energia luminosa'] = 350, ['Energia incandescente'] = 225 },
}

--[[
Function to get the lowest price for multiple choice items
--]]
local function specprice(item)
	local low = 9999999999
	for i,v in pairs( specmats[item] ) do
		local price = geprice(i) * v
		if price <= low then
			low = price
		end
	end
	return low
end

function p.main(frame)
	local args = frame:getParent().args
	--[[
	Function to handle all the materials listed
	Creates a table to pass to _main() consisting of
	* Item name, as a wikilink
	* Item image, as a wikilink, includes link to page
	* Quantity
	* Formatted price for display
	* Clean price for calculations
	If the parameter mat# is defined and not blank
	Every parameter (mat#img, mat#qty, mat#price) will be looked for as well
	--]]
	local function mat_list()
		local ret_list = {}
		for i=1,10,1 do
			local mat = args['mat'..i]
			if mat and params.has_content(mat) then
				local name = params.default_to(args['mat'..i..'nome'],mat)
				-- 2 separate prices
				-- 1 for display
				-- 1 for calculation
				local price,price_raw
				local qty = params.default_to(args['mat'..i..'quantidade'],'1')
				local img = params.default_to(args['mat'..i..'imagem'],
					mat..'.png')
					:gsub('File:','')
				local price_v = params.default_to(args['mat'..i..'preço'],'/')
				-- gemw = use exchange price
				if price_v:lower() == 'gemw' then
					if specmats[mat] then
						price_raw = specprice(mat)
						price = commas._add(price_raw)
					else
						price_raw = geprice(mat)
						price = commas._add(price_raw)
					end
				-- parseable as number = use that
				elseif tonumber(commas._strip(price_v),10) then
					price_raw = tonumber(commas._strip(price_v),10)
					price = commas._add(price_raw)
				-- Some untradeables have a distinct market price
				-- because of their materials
				-- The template {{GETotal}} will help here
				-- Look for template call
				elseif price_v:find('{{.*}}') then
					price_raw = frame:preprocess(price_v)
					price = commas._add(price_raw)
				-- everything else
				-- use N/A for display and 0 for calculations
				else
					price_raw = 0
					price = 'N/D'
				end

				table.insert(ret_list, {
					name = '[['..mat..'|'..name..']]',
					name_raw = mat,
					price = price,
					price_raw = price_raw,
					quantity = qty,
					image = '[[File:'..img..'|link='..mat..']]',
					image_raw = img
				} )
			end
		end
		return ret_list
	end
	--[[
	Function to get a list of additional requirements, should there be any
	Will take non-blank parameters and simply paste them as is into a table
	Which will then be passed into the _main() function
	--]]
	local function get_other_reqs()
		local req_list = {}
		for i=1,5,1 do
			local req = args['misc'..i]
			if req and req:find('%S') then
				table.insert(req_list,req)
			end
		end
		return req_list
	end
	-- Fetching and formatting parameters starting here
	local item_name,item_image,
		ticks,ticks2,ticksnote,
		skill,level,level_old,experience,
		method,improved,instructions,totalvar = params.defaults{
				{args.nome,mw.title.getCurrentTitle().text},
				{args.imagem,nil},
				{args.ticks,editbutton('?')},
				{args.ticks2,nil},
				{args.ticksnota,nil},
				{args.habilidade,nil},
				{args['nível'],'[email protected]'},
				{args['nivel'],'[email protected]'},
				{args.habilidade_exp,nil},
				{args['método'],nil},
				{args.melhorada,0},
				{args['instruções'],nil},
				{args.totalvar,nil}
			}
	if level == '[email protected]' then
		if level_old == '[email protected]' then
			level = editbutton('?')
		else
			level = level_old
		end
	end
	local item_link = mw.title.getCurrentTitle().text

	local skill2,level2,level2_old,experience2,
		facility,quest = params.defaults{
				{args.habilidade_sec,nil},
				{args['nível_sec'],'[email protected]'},
				{args['nivel_sec'],'[email protected]'},
				{args.habilidade_sec_exp,nil},
				{args.facilidade,nil},
				{args['missão'],nil}
			}
	if level2 == '[email protected]' then
		if level2_old == '[email protected]' then
			level2 = nil
		else
			level2 = level2_old
		end
	end
	
	-- Add [[File: and |link=...]] to image, if it's defined
	if item_image then
		item_image = '[[File:'..item_image:gsub('File:','')..'|link='..item_link..']]'
	-- anti-redlink
	elseif mw.title.getCurrentTitle().text == 'Infobox recipe/preload'
			or mw.title.getCurrentTitle().text == 'PreloadPage/Orphanage' then
		item_image = ''
	else
		item_image = '[[File:'..item_name..'.png|link='..item_name..']]'
	end
	-- Allow amount to be removed if it's 1
	local item_amount = tonumber(args.quantidade,10) or 1
	
	-- Check that improved is a number
	if tonumber(improved,10) then
		improved = tonumber(improved,10)
	else
		improved = 0
	end

	-- Tables to pass; call above functions
	local materials = mat_list()
	local misc_reqs = get_other_reqs()

	-- Look for gemw in the parameter, otherwise nil
	local item_ge_v = string.lower(args.mercado or '')
	local item_gep
	if item_ge_v == 'gemw' then
		item_gep = geprice(item_name)
	elseif item_ge_v == 'não' then
		item_gep = 'não'
	else
		item_gep = nil
	end

	-- Only accept "yes" or "no"
	-- Anything else defaults to no
	-- Should this default to unknown instead?
	local members = yesno(args.membros) and '[[File:P2P ícone.png|21px|link=]] Somente para membros' or '[[File:F2P ícone.png|21px|link=]] Gratuito para jogar'

	-- Pass parameters to _main
	return p._main{ frame,
		item_name,
		item_link,
		item_image,
		item_amount,
		ticks,
		ticks2,
		ticksnote,
		improved,
		method,
		materials,
		facility,
		misc_reqs,
		skill,
		level,
		experience,
		skill2,
		level2,
		experience2,
		item_gep,
		members,
		quest,
		yesno(args.nosmw) or false,
		instructions,
		totalvar
	}
end

--
-- Main
--
function p._main(...)
	-- Unpack parameters
	local frame,
		item_name,item_link,
		item_image,item_amount,
		ticks,ticks2,ticksnote,
		improved,method,
		materials,facility,misc_reqs,
		skill,level,experience,
		skill2,level2,experience2,item_gep,
		members,quest,nosmw,instructions,totalvar = unpack(...)
	
	local hasreftag = false

	local ret = mw.html.create('table')
			:addClass('wikitable')
			:css({ width = '50%',
				['max-width'] = '450px' })
	-- Caption header
	local caption = item_image..' '..item_name
	if item_amount > 1 then
		caption = caption..' ×'..item_amount
	end
	if improved > 0 then
		caption = caption..string.format(' <i><span title="Receita melhorada %s">(+%s)</span></i>', improved, improved)
	elseif method then
		caption = caption..string.format('<br /><i>(%s)</i>', method)
	end
	ret:tag('caption'):wikitext(caption):done()

	-- Creation of row 1
	-- Columns 1 and 5
	local row1 = ret:tag('tr')
			:css('text-align','center')

	local row1a = row1:tag('th')
		:css('width','20%')

	if skill then
		if skill:lower() == 'não' then
			row1a:wikitext('-')
		else
			row1a:wikitext(skillpic(skill))
		end
	else
		row1a:wikitext('\'\'? hab\'\' '..editbutton())
	end

	local row1e = row1:tag('th')
		:css('width','20%')

	if skill2 and not (skill2:lower() == 'não') then
		row1e:wikitext(skillpic(skill2))
	else
		row1e:wikitext('-')
	end

	row1:tag('th')
			:attr('title','Ticks por ação')
			:css('width','40%')
			:attr('colspan','2')
			:wikitext('[[Arquivo:Ampulheta.png|link=Tique]]')
		:done()
		:tag('th')
			:attr('title','Preço médio do Mercado Geral')
			:css('width','20%')
			:wikitext('[[Arquivo:Criar-X MG ícone.png|link=]]')
		:done()

	-- Creation of row 2
	local row2 = ret:tag('tr')
		:css('text-align','center')
	local row2a = row2:tag('td')
	local row2b = row2:tag('td')
	local row2c = row2:tag('td')
			:attr('colspan','2')
	local row2d = row2:tag('td')

	if skill and skill:lower() == 'não' then
		row2a:wikitext('-')
	elseif experience then
		row2a:wikitext(commas._add(experience)..' EXP')
	else
		row2a:wikitext('\'\'? EXP\'\' '..editbutton())
	end

	if experience2 then
		row2b:wikitext(commas._add(experience2)..' EXP')
	else
		row2b:wikitext('-')
	end
	
	if tonumber(ticks,10) then
		local secs = tonumber(ticks,10) * 0.6
		local note = ''
		if ticksnote and string.find(ticksnote, '%S') then
			if ticksnote == '1' then
				ticksnote = 'Ao criar um único objeto'
			end
			note = frame:extensionTag{ name='ref', content = ticksnote, args = {group="recipe"} }
			hasreftag = true
		end
		if tonumber(ticks2,10) then
			local secs2 = tonumber(ticks2,10) * 0.6
			row2c:tag('span')
				:attr('title',ticks..' ticks ('..secs..' segundos) por ação')
				:wikitext(ticks..' ('..secs..'s) ')
			:done()
			:wikitext(' / ')
			:tag('span')
				:attr('title',ticks2..' ticks ('..secs2..' segundos) por ação, ')
				:wikitext('<i> '..ticks2..' ('..secs2..'s)</i> ')
			:done()
			:wikitext(note)
		else
			row2c:attr('title',ticks..' ticks ('..secs..' segundos) por ação')
				:wikitext(ticks..' ('..secs..'s) '..note)
		end
	elseif string.lower(ticks) == 'varies' then
		local note = ''
		if ticksnote and string.find(ticksnote, '%S') then
			note = frame:extensionTag{ name='ref', content = ticksnote, args = {group="recipe"} }
			hasreftag = true
		end
		row2c:attr('title', 'Varia')
			:wikitext('Varia ' .. note)
	else
		row2c:wikitext(ticks)
	end

	if item_gep then
		if item_gep == 'não' then
			row2d:attr('title','Não pode ser vendido no Mercado Geral')
				:wikitext('-')
		elseif item_amount > 1 then
			row2d:attr('title',commas._add(item_gep)..' moedas cada')
				:wikitext(commas._add(item_gep * item_amount))
		else
			row2d:wikitext(commas._add(item_gep))
		end
	else
		row2d:wikitext('\'\'?\'\' '..editbutton())
	end

	-- Add "Requirements" header
	ret:tag('tr')
			:tag('th')
				:attr('colspan','5')
				:wikitext('Requisitos')
			:done()
		:done()
	-- Skill requirement 1
	if skill and not (skill:lower() == 'não') then
		ret:tag('tr')
			:tag('td')
				:attr('colspan','4')
				:wikitext(skillpic(skill)..' Nível de '..params.ucflc(skill))
			:done()
			:tag('td')
				:css('text-align','center')
				:wikitext(level)
			:done()
		:done()
	end
	-- Skill requirement 2
	if skill2 and level2 then
		ret:tag('tr')
			:tag('td')
				:attr('colspan','4')
				:wikitext(skillpic(skill2)..' Nível de '..params.ucflc(skill2))
			:done()
			:tag('td')
				:css('text-align','center')
				:wikitext(level2)
			:done()
		:done()
	end

	-- Quest requirement
	if quest and not (quest:lower() == 'não') then
		ret:tag('tr')
			:tag('td')
				:attr('colspan','5')
				:wikitext(skillpic('quest')..' '..quest)
			:done()
		:done()
	end
	
    -- Facility requirement
    function facility_link(facility_arg)
        if type(facility_arg) == 'string' and mapicons.filelink(facility_arg:lower())[1] then
            local link = mapicons.filelink(facility_arg:lower())[2]
            local txt = mapicons.filelink(facility_arg:lower())[3]
            return " [["..link.."|"..(txt or link:lower()).."]]"
        else
            return facility_arg
        end
    end
	
	if facility then
		ret:tag('tr')
			:tag('td')
				:attr('colspan','5')
				:wikitext(mapicons._main(facility)..' Deve ser realizada em um(a) '..facility_link(facility))
			:done()
		:done()
	end

	-- Miscellaneous requirements
	for i, v in ipairs(misc_reqs) do
		ret:tag('tr')
			:tag('td')
				:attr('colspan','5')
				:wikitext(v)
			:done()
		:done()
	end

	-- Members requirement
	ret:tag('tr')
			:tag('td')
				:attr('colspan','5')
				:wikitext(members)
			:done()
		:done()

	-- Materials header
	ret:tag('tr')
		:tag('th')
			:attr('colspan','5')
			:wikitext('Materiais')
		:done()
	:done()
	:tag('tr')
		:tag('th')
			:attr('colspan','2')
			:wikitext('Objeto')
		:done()
		:tag('th')
			:wikitext('Quantidade')
		:done()
		:tag('th')
			:wikitext('Preço')
		:done()
		:tag('th')
			:wikitext('Total')
		:done()
	:done()

	-- Materials
	local total_price = 0
	local valued_items = 0
	-- Iterates through the tables in the table of materials
	for i, v in ipairs(materials) do
		-- Fetch all the variables
		local mat_name = v.name
		local mat_price = v.price
		local mat_raw = v.price_raw
		local mat_ttl
		local mat_qty = v.quantity
		local mat_img = v.image
		-- If no price is given for item, delete total
		-- Otherwise quantity * price each
		if mat_raw == 0 then
			mat_ttl = '-'
		else
			mat_ttl = mat_qty * mat_raw
		end
		-- If item total is a number
		-- Add it to the overall total
		-- Indicate this by incrementing valued item count
		-- Done with total calculations, add commas to total for formatting
		if type(mat_ttl) == 'number' then
			total_price = total_price + mat_ttl
			mat_ttl = commas._add(mat_ttl)
			if mat_raw > 0 then
				valued_items = valued_items + 1
			end
		end
		ret:tag('tr')
			:tag('td')
				:css({ ['border-right'] = 'none',
					['text-align'] = 'center' })
				:wikitext(mat_img)
			:done()
			:tag('td')
				:css({ ['border-left'] = 'none',
					['border-right'] = 'none',
					['text-align'] = 'left' })
				:wikitext(mat_name)
			:done()
			:tag('td')
				:css({ ['border-left'] = 'none',
					['border-right'] = 'none',
					['text-align'] = 'right' })
				:wikitext(commas._add(mat_qty))
			:done()
			:tag('td')
				:css({ ['border-left'] = 'none',
					['text-align'] = 'right' })
				:wikitext(mat_price)
			:done()
			:tag('td')
				:css('text-align','right')
				:wikitext(mat_ttl)
			:done()
		:done()
	end

	-- If no materials found
	-- Indicate nothing listed, add an edit button for the page
	if #materials == 0 then
		ret:tag('tr')
				:tag('td')
					:attr('colspan','5')
					:css({ ['font-style'] = 'italic',
						['text-align'] = 'center' })
					:wikitext('Materials unlisted '..editbutton())
				:done()
			:done()
	end

	-- Total
	-- Hide if less than 2 items have a value
	if valued_items > 1 then
		ret:tag('tr')
			:tag('th')
				:attr('colspan','4')
				:css('text-align','right')
				:wikitext('Preço total')
			:done()
			:tag('td')
				:css('text-align','right')
				:wikitext(commas._add(total_price))
			:done()
		:done()
	end
	if type(totalvar) == 'string' and #totalvar > 0 then
		mw.ext.VariablesLua.vardefine(totalvar, total_price)
	end
	
	-- Profit
	if valued_items >= 1 then
		if item_gep and item_gep ~= 'não' then
			local profit = item_gep * item_amount - total_price
			local profclass = 'text-green'
			if profit < 0 then
				profclass = 'text-red'
			end
			ret:tag('tr')
				:tag('th')
					:attr('colspan','4')
					:css('text-align','right')
					:wikitext('Lucro')
				:done()
				:tag('td')
					:css('text-align','right')
					:addClass(profclass)
					:wikitext(commas._add(profit))
				:done()
			:done()
		end
	end
	
	if instructions then
		ret:tag('tr')
			:tag('th')
				:attr('colspan','6')
				:css('text-align','center')
				:wikitext('Instruções')
			:done()
		:done()
		:tag('tr')
			:tag('td')
				:attr('colspan','6')
				:wikitext(instructions)
	end

	if onmain and not nosmw then
		smw = {}
		table.insert(smw,'Materiais necessários:')
		local jsonmats = {}
		for _, v in ipairs(materials) do
			table.insert(jsonmats,{ name = v.name_raw, quantity = v.quantity, image = v.image_raw })
			table.insert(smw,string.format('[[Made from item::%s]]',v.name_raw))
		end
		
		if tonumber(ticks,10) then
			table.insert(smw,string.format('[[Production ticks::%s]]',ticks))
		end
		if tonumber(ticks2,10) then
			table.insert(smw,string.format('[[Production ticks secondary::%s]]',ticks))
		end
		if ticksnote and string.find(ticksnote, '%S') then
			table.insert(smw,string.format('[[Production ticks note::%s]]',ticksnote))
		end

		local tojson = {
			product = item_name,
			link = item_link,
			image = item_image,
			ticks = ticks,
			improved = improved,
			method = method or '',
			facility = facility or '',
			mats = jsonmats,
			skill = skill or '?',
			level = tonumber(level) or '?',
			exp = tonumber(experience) or '?',
			experience = tonumber(experience) or '?', -- both for legacy support
			skill2 = skill2 or '?',
			level2 = tonumber(level2) or '?',
			exp2 = tonumber(experience2) or '?',
			experience2 = tonumber(experience2) or '?', -- both for legacy support
			quantity = item_amount
		}
		mw.logObject(tojson)
		local json = mw.text.nowiki(mw.text.jsonEncode(tojson))

		table.insert(smw,'- - - - - - - - - -')
		table.insert(smw,'Production JSON:')
		table.insert(smw,string.format('[[Production JSON::%s]]',json))
		ret	:tag('div')
				:attr('smw-infobox-data')
				:addClass('hidden')
				:css('display','none')
				:wikitext(table.concat(smw,'\n'))
			:done()
	end
	
	-- Add categories
	cats = {}
	if not skill then
		table.insert(cats,'Criação sem habilidade')
	end
	if skill and not (skill:lower() == 'não') then
		if not experience then
			table.insert(cats,'Criação sem EXP ')
		end
		if not tonumber(level,10) then
			table.insert(cats,'Criação sem nível de habilidade')
		end
	end
	if not tonumber(ticks,10) and string.lower(ticks) ~= 'varies' then
		table.insert(cats,'Criação sem ticks')
	end
	if not item_gep then
		table.insert(cats,'Criação sem valores de objetos')
	end
	
	for i, v in ipairs(cats) do
		if (v ~= '') then
			cats[i] = string.format('[[Categoria:%s]]',v)
		end
	end
	local outro = ''
	if hasreftag then
		outro = '\n' .. frame:extensionTag{ name='references', args = {group="recipe"} }
	end
	return tostring(ret)..table.concat(cats,'')..outro
end

return p