Перайсьці да зьместу

Модуль:Цёзкі

Зьвесткі зь Вікіпэдыі — вольнай энцыкляпэдыі
--------------------------------------------------------------------------------
-- Гэты модуль апрацоўвае {{Цёзкі}}
--
-- Для выкарыстаньня праз {{#invoke:…}} выкарыстоўвайце «{{#invoke:Цёзкі|main|{{{1|}}}}}»
--
-- Модуль працуе як зь імем, так і з прозьвішчам, аўтаматычна вызначая іх, калі парамэтар {{{1|}}} не зададзены,
-- а таксама заўсёды вызначае выгляд шаблёну аўтаматычна.
--------------------------------------------------------------------------------
local mHatnote = require('Модуль:Іншае значэньне')
local mArguments = require('Модуль:Аргумэнты')
local mFormatLink = require('Модуль:Фармат спасылкі')

local p = {}

local function trim(s)
	if not s then return '' end
	return (s:gsub('^%s+', ''):gsub('%s+$', ''))
end

local function stripMarkup(s)
	if not s then return '' end
	s = trim(s)
	s = s:gsub('^%[%[', ''):gsub('%]%]$', '')
	s = s:gsub('|.*$', '')
	s = s:gsub('#.*$', '')
	return trim(s)
end

local lower = mw.ustring and mw.ustring.lower or string.lower
local function norm(s)
	return lower(trim(s or ''))
end

local function splitWords(s)
	local t = {}
	for w in (s or ''):gmatch('[^%s]+') do
		table.insert(t, w)
	end
	return t
end

local function makeLinkSafe(s)
	if not s or s == '' then return '' end
	if s:match('^%[%[.*%]%]$') then
		return s
	end
	return tostring(mFormatLink._formatLink{ link = s })
end

local function existsPage(title)
	if not title or title == '' then return false end
	local t = mw.title.new(title)
	if t and t.exists then return true end
	t = mw.title.new(title .. ' (неадназначнасьць)')
	return t and t.exists
end

local function getDisambiguationTitle(baseTitle)
	local disambigTitle = baseTitle .. ' (неадназначнасьць)'
	local t = mw.title.new(disambigTitle)
	return t and t.exists and disambigTitle or baseTitle
end

function p.main(frame)
	local args = mArguments.getArgs(frame, { wrappers = 'Шаблён:Цёзкі' })
	local rawParam = trim(args[1])

	local thisTitle = frame:getParent() and frame:getParent().title or mw.title.getCurrentTitle()
	local titleText = mw.ustring.gsub(thisTitle.text, '%s%b()$', '')
	local normCurrent = norm(titleText)
	local ns = thisTitle.namespace

	local titleWords = splitWords(titleText)
	local given = titleWords[1] or ''
	local family = (#titleWords >= 2) and table.concat(titleWords, ' ', 2) or ''
	local fullName = trim(given .. ' ' .. family)

	if rawParam ~= '' then
		local paramText = trim(rawParam)
		local paramWords = splitWords(stripMarkup(paramText))
		local link = makeLinkSafe(paramText)

		local fullMatch = true
		for _, w in ipairs(splitWords(fullName)) do
			local lw = norm(w)
			local found = false
			for _, pw in ipairs(paramWords) do
				if norm(pw) == lw then
					found = true
					break
				end
			end
			if not found then
				fullMatch = false
				break
			end
		end

		if fullMatch then
			return mHatnote._hatnote(
				'У Вікіпэдыі ёсьць артыкулы пра іншых людзей з такімі ж імем і прозьвішчам: ' ..
				link .. '.',
				{}
			)
		end

		local hasGiven, hasFamily = false, false
		for _, w in ipairs(paramWords) do
			if norm(w) == norm(given) then hasGiven = true end
			for _, f in ipairs(splitWords(family)) do
				if norm(w) == norm(f) then hasFamily = true end
			end
		end

		if hasGiven then
			return mHatnote._hatnote(
				'У Вікіпэдыі ёсьць артыкулы пра іншых людзей зь імем ' .. link .. '.',
				{}
			)
		end

		if hasFamily then
			return mHatnote._hatnote(
				'У Вікіпэдыі ёсьць артыкулы пра іншых людзей з прозьвішчам ' .. link .. '.',
				{}
			)
		end

		return mHatnote._hatnote(
			'У Вікіпэдыі ёсьць артыкулы пра іншых людзей, якія ёсьць поўнымі ці няпоўнымі цёзкамі гэтай асобы, глядзіце ' ..
			link .. '.',
			{}
		)
	end

	local foundLinks = {}

	if given ~= '' and norm(given) ~= normCurrent then
		local disambigTitle = getDisambiguationTitle(given)
		if existsPage(disambigTitle) then
			table.insert(foundLinks, {text = 'зь імем ' .. makeLinkSafe(disambigTitle), type = 'name'})
		end
	end

	if family ~= '' and norm(family) ~= normCurrent then
		local disambigTitle = getDisambiguationTitle(family)
		if existsPage(disambigTitle) then
			table.insert(foundLinks, {text = 'з прозьвішчам ' .. makeLinkSafe(disambigTitle), type = 'family'})
		end
	end

	if fullName ~= '' and norm(fullName) ~= normCurrent then
		local disambigTitle = getDisambiguationTitle(fullName)
		if existsPage(disambigTitle) then
			table.insert(foundLinks, {text = 'з такімі ж імем і прозьвішчам: ' .. makeLinkSafe(disambigTitle), type = 'full'})
		end
	end

	-- Калі Аўтавызначэньне нічога не знайшло
	if #foundLinks == 0 then
		if family ~= '' then
			local fakeDis = family .. ' (неадназначнасьць)'
			local fakeLink = makeLinkSafe(fakeDis)
			local note = mHatnote._hatnote(
				'У Вікіпэдыі ёсьць артыкулы пра іншых людзей з прозьвішчам ' .. fakeLink .. '.',
				{}
			)
			if ns == 0 then
				return note .. '\n' .. '[[Катэгорыя:Вікіпэдыя:Артыкулы зь няіснымі старонкамі ў шаблёне «Цёзкі»]]'
			else
				return note
			end
		else
			if ns == 0 then
				return '[[Катэгорыя:Вікіпэдыя:Артыкулы з пустым шаблёнам «Цёзкі»]]'
			end
			return ''
		end
	end

	if #foundLinks == 1 then
		return mHatnote._hatnote(
			'У Вікіпэдыі ёсьць артыкулы пра іншых людзей ' .. foundLinks[1].text .. '.',
			{}
		)
	elseif #foundLinks == 2 then
		local text1 = foundLinks[1].type == 'name' and foundLinks[1].text:gsub('зь імем ', '') 
			or foundLinks[1].text:gsub('з прозьвішчам ', '')
		local text2 = foundLinks[2].type == 'name' and foundLinks[2].text:gsub('зь імем ', '') 
			or foundLinks[2].text:gsub('з прозьвішчам ', '')
		return mHatnote._hatnote(
			'У Вікіпэдыі ёсьць артыкулы пра іншых людзей зь імем ' .. text1 ..
			' і прозьвішчам ' .. text2 .. '.',
			{}
		)
	else
		local fullLink, nameLink, familyLink
		for _, link in ipairs(foundLinks) do
			if link.type == 'full' then fullLink = link
			elseif link.type == 'name' then nameLink = link
			elseif link.type == 'family' then familyLink = link
			end
		end
		if fullLink then
			return mHatnote._hatnote(
				'У Вікіпэдыі ёсьць артыкулы пра іншых людзей ' .. fullLink.text .. '.',
				{}
			)
		elseif nameLink and familyLink then
			local text1 = nameLink.text:gsub('зь імем ', '')
			local text2 = familyLink.text:gsub('з прозьвішчам ', '')
			return mHatnote._hatnote(
				'У Вікіпэдыі ёсьць артыкулы пра іншых людзей зь імем ' .. text1 ..
				' і прозьвішчам ' .. text2 .. '.',
				{}
			)
		else
			return mHatnote._hatnote(
				'У Вікіпэдыі ёсьць артыкулы пра іншых людзей ' .. foundLinks[1].text .. '.',
				{}
			)
		end
	end
end

return p