FANDOM


local p = {}
 
-- Genera la clase del contenedor
local function getContainerClassName( align )
	local className = 'article-thumb'
	if align == 'left' or arg == 'right' or arg == 'none' then
		className = className .. string.format( ' t%s', align )
	end
	className = className .. ' video'
	return className
end
 
-- Obtiene un número para el tamaño, o usa el valor por defecto
local function getIntOrDefaultToString( val, defVal )
	local num = tonumber( val, 10 )
	if not num or num <= 0 then
		num = defVal
	end
	return string.format( '%d', num )
end
 
-- Extrae el video id de la URL, o del id directamente, comprobando que sea correcto
-- El video id es de 11 caracteres
local function getVideoId( part )
	local m
	if not part then
		return nil
	end
	part = mw.text.trim( part )
	if #part == 11 then
		return string.match( part, '^[0-9A-Za-z_-]+$' )
	end
	m = string.match( part, 'youtube\.com/watch.-[?&]v=([0-9A-Za-z_-]+)' )
	if m and #m == 11 then
		return m
	end
	m = string.match( part, 'youtube\.com/embed/([0-9A-Za-z_-]+)' )
	if m and #m == 11 then
		return m
	end
	m = string.match( part, 'youtube\.com/v/([0-9A-Za-z_-]+)' )
	if m and #m == 11 then
		return m
	end
	m = string.match( part, 'youtu\.be/([0-9A-Za-z_-]+)' )
	if m and #m == 11 then
		return m
	end
end
 
--[[ ------------------
-- Función principal
------------------ ]]--
function p.main( frame )
	local containerDiv, ytid, parent
	parent = frame:getParent()
	ytid = getVideoId( parent.args['video'] or parent.args[1] )
	containerDiv = mw.html.create( 'div' )
		:attr( 'class', getContainerClassName( parent.args['align'] ) )
		:css( 'width', getIntOrDefaultToString( parent.args['width'], 300 ) .. 'px' )
	if  ytid then
		containerDiv:tag( 'div' )
			:attr( 'class', 'youtube' )
			:css( 'width', getIntOrDefaultToString( parent.args['width'], 300 ) .. 'px' )
			:css( 'height', getIntOrDefaultToString( parent.args['width'], 233 ) .. 'px' )
			:css( 'position', 'relative' )
			:attr( 'data-youtubevid', ytid )
			:done()
	else
		containerDiv:tag( 'div' )
			:attr( 'class', 'error' )
			:wikitext( 'Error: No se reconoce el identificador del vídeo o la URL de Youtube.' )
			:done()
	end
	if parent.args['texto'] or parent.args[2] then
		containerDiv:tag( 'div' )
			:addClass( 'thumbcaption' )
			:wikitext( parent.args['texto'] or parent.args[2] )
			:done()
	end
	return tostring(containerDiv)
end
 
return p