ניתן ליצור תיעוד על היחידה הזאת בדף יחידה:מדיה/תיעוד

local p = {}

local getArgs = require('Module:Arguments').getArgs

local function trim(s)
	if type(s) ~= 'string' then return '' end
	return mw.text.trim(s)
end

local function isBlank(s)
	return trim(s) == ''
end

-- Fetch first P51 (commonsMedia) and legend P2096 with language fallback
local function getP51AndLegend(entityId)
	if not entityId or isBlank(entityId) then
		entityId = mw.wikibase.getEntityIdForCurrentPage()
		if not entityId then return nil, nil end
	end

	local statements = mw.wikibase.getBestStatements(entityId, 'P51') or {}
	if #statements == 0 then return nil, nil end

	local st = statements[1]
	local mainsnak = st and st.mainsnak
	if not (mainsnak and mainsnak.datavalue and mainsnak.datavalue.value) then
		return nil, nil
	end

	local filename = mainsnak.datavalue.value  -- commonsMedia filename

	-- Collect legend in preferred langs
	local legendByLang = {}
	if st.qualifiers and st.qualifiers.P2096 then
		for _, q in ipairs(st.qualifiers.P2096) do
			local dv = q.datavalue and q.datavalue.value
			if dv and dv.text and dv.language then
				legendByLang[dv.language] = legendByLang[dv.language] or dv.text
			end
		end
	end

	local legend = legendByLang['he'] or legendByLang['en'] or ''
	return filename, legend
end

local function renderBox(args)
	local align = trim(args['יישור'] or '')
	local name  = trim(args['שם']   or '')
	local desc  = trim(args['תיאור'] or '')
	local size  = trim(args['גודל'] or '')
	local qid   = trim(args['qid'] or args['פריט'] or '')

	-- Fallback to Wikidata if needed
	if isBlank(name) or isBlank(desc) then
		local wdName, wdLegend = getP51AndLegend(qid)
		if isBlank(name) and wdName then name = wdName end
		if isBlank(desc) and wdLegend then desc = wdLegend end
	end

	-- If still no filename, do nothing (avoid broken links)
	if isBlank(name) then
		return ''
	end

	-- Description may stay empty (“make it with no text”)
	local floatStyle = (align == 'שמאל') and ' style="float:left;"' or ''
	
	local title = desc
	
	if not isBlank(size) then
		if isBlank(title) then
			title = 'מדיה (' .. size .. ')'
		else
			title = title .. ' - (' .. size .. ')'
		end
	end

	if isBlank(title) then
		title = '‎'
	end
	
	local out = {}
	table.insert(out, '{|' .. floatStyle)
	table.insert(out, '|-')
	table.insert(out, '| rowspan=2 |[[קובץ:Multimedia-icon.svg|25px]]')
	table.insert(out, '| [[:קובץ:' .. name .. '|' .. title .. ']] [[קובץ:' .. name .. '|noicon]]')
	table.insert(out, '|-')
	table.insert(out, '| style="font-size: 75%; padding: 0; margin: 0;" | [[עזרה:מדיה|לעזרה בהפעלת הקובץ]]')
	table.insert(out, '|}')
	return table.concat(out, '\n')
end

function p.main(frame)
	-- getArgs pulls from parent template automatically
	local args = getArgs(frame, { removeBlanks = false })
	return renderBox(args)
end

return p