Документация
local p = {}

-- Константы
local contentLanguageCode = mw.getContentLanguage():getCode();

function p.formatCommonsCategory( context, options, value )
    local link = 'commons:Category:' .. value
    local title = value .. ' на Викискладе'
    if ( options['text'] and options['text'] ~= '' ) then
    	title = options['text']
    end

	commons = '[[' .. link .. '|' .. title .. ']]'

	--Commons icon
    if ( not options['icon'] or options['icon'] ~= '-' ) then
    	local icon_size = '15px'
    	if ( options['icon_size'] and options['icon_size'] ~= '' ) then
    		icon_size = options['icon_size']
    	end
    	commons = '[[File:Commons-logo.svg|' .. icon_size .. '|link=' .. link .. '|alt=Логотип Викисклада]] ' .. commons
    end

	--Text before and after link
    if ( options['text_before'] and options['text_before'] ~= '' ) then
    	if ( options['text_before'] ~= '-' ) then
	    	commons = options['text_before'] .. ' ' .. commons
	    end
    end

    if ( options['text_after'] and options['text_after'] ~= '' ) then
    	if ( options['text_after'] ~= '-' ) then
	    	commons =  commons .. ' ' .. options['text_after']
	    end
    end
	
    return commons
end

--[[
	Временный хак, нужно добавить config, getConfig и getCategoryByCode
	в options, чтобы они были доступны в любом месте кода.
]]
local config;
local function getCategoryByCode( code, sortkey )
	if config == nil then
		config = require( 'Module:Wikidata/config' );
	end;

	local value = config[ 'categories' ][ code ];
	if not value or value == '' then
		return '';
	end
	
	return '[[Category:' .. value .. ']]';
end

local function getCaption( context, options )
	local caption = ''
	if options.qualifiers and options.qualifiers.P2096 then
		for i, qualifier in pairs( options.qualifiers.P2096 ) do
			if ( qualifier
					and qualifier.datavalue
					and qualifier.datavalue.type == 'monolingualtext'
					and qualifier.datavalue.value
					and qualifier.datavalue.value.language == contentLanguageCode ) then
				caption = qualifier.datavalue.value.text
				break
			end
		end
	end
	if options['appendTimestamp'] and options.qualifiers and options.qualifiers.P585 and options.qualifiers.P585[1] then
		local moment = context.formatValueDefault( context, options, options.qualifiers.P585[1].datavalue )
		if not caption or caption == ''  then 
			caption = moment
		else
			caption = caption .. ', ' .. moment
		end
	end

	local localValue = '';
	if options[ 'value' ] and options[ 'value' ] ~= '' then
		localValue = options[ 'value' ];
	end
	
	local localCaption = '';
	if options[ 'caption' ] and options[ 'caption' ] ~= '' then
		localCaption = options[ 'caption' ];
	end
	
	if localValue ~= '' then
		caption = localCaption;
	end
	
	local formattedCaption = ''
	if caption ~= '' then
		formattedCaption = context.wrapQualifier( caption, 'P2096', { class = 'media-caption', style = 'display:block' } );
	end

	if localValue == '' and localCaption ~= '' then
		formattedCaption = formattedCaption .. getCategoryByCode( 'media-contains-local-caption' )
		if options.frame:preprocess('{{REVISIONID}}') == '' then
			formattedCaption = formattedCaption .. '<span class="error" style="font-size:94%;">Локальная подпись не используется, потому что изображение берётся из Викиданных, см. [[Википедия:Шаблоны-карточки#Описание изображения в Викиданных|здесь]]</span>'
		end
	end

	return caption, formattedCaption
end

function p.formatCommonsMediaValue( context, options, value )
	local image = value;
	local caption, formattedCaption = getCaption( context, options )
	
	if not string.find( value, '[%[%]%{%}]' ) and not string.find( value, 'UNIQ%-%-imagemap' ) then
		-- если в value не содержится викикод или imagemap, то викифицируем имя файла
		-- ищем слово imagemap в строке, потому что вставляется плейсхолдер: [[PHAB:T28213]]
		image = '[[File:' .. value .. '|frameless';
		if options[ 'border' ] and options[ 'border' ] ~= '' then
			image = image .. '|border';
		end

		local size = options[ 'size' ];
		if size and size ~= '' then
			if not string.match( size, 'px$' )
				and not string.match( size, 'пкс$' ) -- TODO: использовать перевод для языка вики
			then
				size = size .. 'px'
			end
			
			-- временно
			if string.match( size, 'pxpx' ) then
				image = '[[Категория:Википедия:Изображение с pxpx в размере]]' .. image
			end
		else
			size = fileDefaultSize;
		end
		image = image .. '|' .. size;

		if options[ 'alt' ] and options[ 'alt' ] ~= '' then
			image = image .. '|alt=' .. options[ 'alt' ];
		end
		
		if caption ~= '' then
			image = image .. '|' .. caption
		end
		image = image .. ']]';

		if formattedCaption ~= '' then
			image = image .. '<br>' .. formattedCaption;
		end
	else
		image = image .. formattedCaption .. getCategoryByCode( 'media-contains-markup' );
	end
	
	if options.entity and options.fixdouble then
		local page = mw.title.getCurrentTitle()
		local txt = page:getContent()
		if txt and txt:match(':' .. value) and mw.title.getCurrentTitle():inNamespace(0) then
			if options.frame:preprocess('{{REVISIONID}}') == '' then
				image = image .. '<span class="error">Это изображение встречается ниже по тексту статьи; пожалуйста, уберите одну из копий (не потеряв при этом подпись)</span>'
			end
			image = image .. getCategoryByCode( 'media-contains-local-double' )
		end
	end
	
	return image
end

return p