ХӀокху модулах лаьцна хааман Модуль:TerritorialDivision/doc агӀо кхолла мега

local p = {}

local function Declension(collocation, case)
	local str = string.match(collocation, "([^\(]+)")
	if case == Genitive then
		if string.match(str, "ан кӀошт") then
			return string.gsub( str, "ан кӀошт", "ан кӀоштан" )
		elseif string.match(str, "ан автономин область") then
			return string.gsub( str, "ан автономин область", "ан автономин областан" )
		elseif string.match(str, "ан гӀалин гуо") then
			return string.gsub( str, "ан гӀалин гуо", "ан гӀалин гуонан" )
		elseif string.match(str, "ан гӀалин гуо") then
			return string.gsub( str, "ан гӀалин гуо", "ан гӀалин гуонан" )
		elseif string.match(str, "ГӀалин гуо") then
			return string.gsub( str, "ГӀалин гуо", "гӀалин гуонан" )
		elseif string.match(str, "гӀалин гуо") then
			return string.gsub( str, "гӀалин гуо", "гӀалин гуонан" )
		end
	end
end

local function ReplaceDouble(a)
    a=mw.ustring.gsub( a, "([АаОоУуЮюЯя])[Ьь]", "%1ӑ" )
    a=mw.ustring.gsub( a, "([Кк])[Хх]", "%1ӌ" )
    a=mw.ustring.gsub( a, "([Кк])[Ъъ]", "%1ӎ" )
    a=mw.ustring.gsub( a, "([Хх])[Ьь]", "%1ӎ" )
    a=mw.ustring.gsub( a, "Ӏ", "ӏ" )
    return a
end	

local function SortChechen(a, b)
  	a = ReplaceDouble(a)
  	b = ReplaceDouble(b)
    local LenA = mw.ustring.len(a)
    local LenB = mw.ustring.len(b)
    for i = 1, (LenA < LenB) and LenA or LenB do
        if mw.ustring.codepoint(a, i, i) ~= mw.ustring.codepoint(b, i, i) then
            return mw.ustring.codepoint(a, i, i) < mw.ustring.codepoint(b, i, i)
        end
    end
    return LenA < LenB
end

function p.MakeMunicipality(frame)
    local args = frame:getParent().args
	if args[1]==nil then 
    	CallSite = mw.wikibase.getEntityObject() 
    else
    	CallSite = mw.wikibase.getEntityObject(string.match( args[1], "Q%d+")) 
    end
    if CallSite==nil then do return "[[Категори:Не удалось получить свойства района из викидаты]]" end end
    local District

	if CallSite.claims.P31 and CallSite.claims.P31[1].mainsnak.datavalue.value['id'] == "Q2198484" then 
		District = CallSite
	elseif (CallSite.claims.P31 and CallSite.claims.P31[1].mainsnak.datavalue.value['id'] == "Q634099") or
		(CallSite.claims.P31 and CallSite.claims.P31[1].mainsnak.datavalue.value['id'] == "Q2661988") then 
		District = mw.wikibase.getEntityObject( CallSite.claims.P131 and CallSite.claims.P131[1].mainsnak.datavalue.value['id'] )
	else
		do return "Неизвестный тип поселения. Сообщите, пожалуйста, на страницу обсуждения шаблона" end
    end
    if District == nil then do return "[[Категори:Не удалось получить свойства района из викидаты]]" end end

    DistrictName = District:getSitelink() or District:getLabel()
	
	local Colour   = args['бос'] or "{{Бос|Росси}}"
	local Titul    = args['корта'] or "Муниципалан кхоллам [[" .. DistrictName .. "|" ..  Declension(DistrictName, Genitive) .. "]]"
	local State    = args['state'] or (#District.claims.P150 > 20 and "<includeonly>collapsed</includeonly>")
	local Picture  = args['сурт'] or (District.claims.P94 and "[[Файл:" .. District.claims.P94[1].mainsnak.datavalue['value'] .. "|60px]]")
	local Picture2 = args['сурт2'] or (District.claims.P41 and "[[Файл:" .. District.claims.P41[1].mainsnak.datavalue['value'] .. "|80px|border]]") 

	local frameTable={}
	table.insert( frameTable,  "{{навигацин аса")
	table.insert( frameTable, "|цӀе = Муниципалан кхоллам")
	table.insert( frameTable,  "|бос = " .. Colour)
	table.insert( frameTable, "|корта= " .. Titul)
	if State then table.insert( frameTable, "|state = " .. State) end
	if Picture then table.insert( frameTable, "|сурт = " .. Picture) end
	if Picture2 then table.insert( frameTable, "|сурт2 = " .. Picture2) end
	table.insert( frameTable, "|чулацам = ")
	local GorodMO={}
	local SeloMO={}
	for c, claim in pairs( District.claims.P150 ) do
		if ( claim['rank'] ~= "deprecated" and claim.mainsnak.datavalue.value['id'] ) then
			local childQ = claim.mainsnak.datavalue.value['id']
		    local Child = mw.wikibase.getEntityObject( childQ )
			if Child.claims.P31 and Child.claims.P31[1].mainsnak.datavalue.value['id'] == "Q634099" then 
		    	table.insert (SeloMO, Child:getSitelink()  or Child:getLabel())
		    elseif Child.claims.P31 and Child.claims.P31[1].mainsnak.datavalue.value['id'] == "Q2661988" then 
		    	table.insert (GorodMO, Child:getSitelink()  or Child:getLabel())
		    else			
		    	do return "Неизвестный тип поселения" end
		    end
		end
	end

	table.sort(GorodMO)
	for key, val in pairs(GorodMO) do
   		table.insert( frameTable, "{{s|[[" .. val .. "|" .. string.match(val, "([^\(]+)") .. "]]}}{{•}}" )
	end	
	frameTable[#frameTable] = string.gsub( frameTable[#frameTable], "}}{{•}}$", "}}<br>") 

	table.sort(SeloMO)
	SeloStr=""
	for key, val in pairs(SeloMO) do
   		table.insert( frameTable, "{{s|[[" .. val)
   		if string.match(val, "%(") then table.insert( frameTable, "|" .. string.match(val, "([^\(]+) %(")) end
   		table.insert( frameTable, "]]}}{{•}}")
	end	
	frameTable[#frameTable] = string.gsub( frameTable[#frameTable], "}}{{•}}$", "}}") 
	table.insert( frameTable, "}}")
	frameStr=table.concat(frameTable)

	return frame:preprocess( frameStr ) 
end

-- ================================================================================================================================
function p.MakeSettlements (frame)
    local args = frame:getParent().args
	SiteExist = false
	CategoryError = "[[Категори:Википеди:Статьи с некорректным применением шаблона КӀоштан нах беха меттигаш]]"
	if args[1]==nil then 
    	CallSiteQ = mw.wikibase.getEntityIdForCurrentPage()
    	CallSite = mw.wikibase.getEntityObject() 
    else
    	CallSiteQ = string.match( args[1], "Q%d+")
    	if CallSiteQ then CallSite = mw.wikibase.getEntityObject(CallSiteQ) end
    end
    if CallSite==nil then do return "[[Категори:Не удалось получить свойства района из викидаты]]" .. CategoryError end end
    local District
    local TypeMO = "МР"

	if  CallSite.claims.P576 then 
		do return "[[Категори:ДӀайаьхна нах беха меттигаш N-ан кӀоштан]]" end
		--Parent = mw.wikibase.getEntityObject( CallSite.claims.P131 and CallSite:getBestStatements( "P131" )[1].mainsnak.datavalue.value['id'] )
		--District = mw.wikibase.getEntityObject( Parent.claims.P131 and Parent:getBestStatements( "P131" )[1].mainsnak.datavalue.value['id'] )
		--if District.claims.P31 and District.claims.P31[1].mainsnak.datavalue.value['id'] ~= "Q2198484" then District = nil do return "[[Категори:Не удалось получить свойства района из викидаты]]".. CategoryError end end
	    -- DistrictName = District:getSitelink("cewiki") or District:getLabel("ce")
		-- do return "[[Категори: " .. DistrictName .. "ан  дӀайаьхна нах беха меттигаш]]" end
	elseif CallSite.claims.P31 and CallSite.claims.P31[1].mainsnak.datavalue.value['id'] == "Q2198484" then 
		District = CallSite
		SiteExist = true
		TypeMO = "МР"
	elseif CallSite.claims.P31 and CallSite.claims.P31[1].mainsnak.datavalue.value['id'] == "Q13626398" then 
		District = CallSite
		SiteExist = true
		TypeMO = "ГО"
	else
    	Parent = mw.wikibase.getEntityObject( CallSite.claims.P131 and CallSite:getBestStatements( "P131" )[1].mainsnak.datavalue.value['id'] )
		if Parent.claims.P31 and Parent.claims.P31[1].mainsnak.datavalue.value['id'] == "Q2198484" then 
			District = Parent
			TypeMO = "МР"
		elseif Parent.claims.P31 and Parent.claims.P31[1].mainsnak.datavalue.value['id'] == "Q13626398" then 
			District = Parent
			TypeMO = "ГО"
		else
			District = mw.wikibase.getEntityObject( Parent.claims.P131 and Parent:getBestStatements( "P131" )[1].mainsnak.datavalue.value['id'] )
			if District.claims.P31 and District.claims.P31[1].mainsnak.datavalue.value['id'] == "Q2198484" then 
				TypeMO = "МР"
			elseif Parent.claims.P31 and Parent.claims.P31[1].mainsnak.datavalue.value['id'] == "Q13626398" then 
				TypeMO = "ГО"
			else
				District = nil 
		    end
	    end
    end
    if District == nill then do return "[[Категори:Не удалось получить свойства района из викидаты]]".. CategoryError end end
	if District.claims.P150 == nill then do return "[[Категори:Не удалось получить свойства района из викидаты]]".. CategoryError end end
	
    DistrictName = District:getSitelink("cewiki") or District:getLabel("ce")
    AdmCenterQ = District:getBestStatements( "P36" )[1].mainsnak.datavalue.value['id'] 
    --AdmCenterQ = District.claims.P36 and District.claims.P36[1].mainsnak.datavalue.value['id']
	AdmCenter = mw.wikibase.getEntityObject( AdmCenterQ )
	AdmCenterName = AdmCenter:getSitelink() or AdmCenter:getLabel()

	local Colour   = args['бос'] or "{{Бос|Росси}}"
	local Titul
	if TypeMO == "МР" then
		Titul = args['корта'] or "[[" .. DistrictName .. "|" .. string.gsub(string.gsub(DistrictName, "кӀошт", "кӀоштан"), " %(.+%)", "") .. "]] нах беха меттигаш"
	else
		Titul = args['корта'] or "[[" .. DistrictName .. "|" .. string.gsub(DistrictName, " %(.+%)", "") .. "]] нах беха меттигаш"
	end
	--do return DistrictName end
	local State    = args['state'] or (#District.claims.P150 > 20 and "<includeonly>collapsed</includeonly>")
	local Picture  = args['сурт'] or (District.claims.P94 and "[[Сурт:" .. District.claims.P94[1].mainsnak.datavalue['value'] .. "|60px]]")
	local Picture2 = args['сурт2'] or (District.claims.P41 and "[[Сурт:" .. District.claims.P41[1].mainsnak.datavalue['value'] .. "|80px|border]]") 

	local frameTable={}
	table.insert( frameTable, "{{Навигацин аса")
	table.insert( frameTable, "|цӀе = КӀоштан нах беха меттигаш")
	table.insert( frameTable, "|бос = " .. Colour)
	if Titul then table.insert( frameTable, "|корта = " .. Titul) end
	if State then table.insert( frameTable, "|state = " .. State) end
	if Picture then table.insert( frameTable, "|сурт = " .. Picture) end
	if Picture2 then table.insert( frameTable, "|сурт2 = " .. Picture2) end
	table.insert( frameTable, "|чулацам = ")

	local AdmCenterExist = false
	local Settlements={}
	if District.claims.P150 then
		for d, DistrictClaim in pairs( District.claims.P150 ) do
			if ( DistrictClaim['rank'] ~= "deprecated" and DistrictClaim.mainsnak.datavalue.value['id'] ) then
				local MunicipalityQ = DistrictClaim.mainsnak.datavalue.value['id']
			    local Municipality = mw.wikibase.getEntityObject( MunicipalityQ )
			    if Municipality.claims.P150 then
					for m, MunicipalityClaim in pairs( Municipality.claims.P150 ) do
						if ( MunicipalityClaim['rank'] ~= "deprecated" and MunicipalityClaim.mainsnak.datavalue.value['id'] ) then
							local SettlementQ = MunicipalityClaim.mainsnak.datavalue.value['id']
						    --local Settlement = mw.wikibase.getEntityObject( SettlementQ )
							if AdmCenterQ == SettlementQ then
						    	AdmCenterExist = true
						    else
						    	--table.insert (Settlements, Settlement:getSitelink()  or Settlement:getLabel())
						    	table.insert (Settlements, mw.wikibase.sitelink(SettlementQ)  or mw.wikibase.label(SettlementQ))
						    end
						    SiteExist = SiteExist or ( SettlementQ == CallSiteQ )
						end
					end
				else
					if AdmCenterQ == MunicipalityQ then
				    	AdmCenterExist = true
				    else
				    	--table.insert (Settlements, Settlement:getSitelink()  or Settlement:getLabel())
				    	table.insert (Settlements, mw.wikibase.sitelink(MunicipalityQ)  or mw.wikibase.label(MunicipalityQ))
				    end
				    SiteExist = SiteExist or ( MunicipalityQ == CallSiteQ )
				end
			end
		end
	end
	if TypeMO == "МР" then
		table.insert( frameTable, 	"'''КӀоштан центр:''' [[" .. AdmCenterName)
	else
		table.insert( frameTable, 	"'''Административан центр:''' [[" .. AdmCenterName)
	end

   	if string.match(AdmCenterName, "%(") then table.insert( frameTable, "|" .. string.match(AdmCenterName, "([^\(]+) %(")) end
   	table.insert( frameTable, "]]")
	if not AdmCenterExist then table.insert( frameTable, " (кӀоштан йукъайогӀуш йац)") end
	table.insert( frameTable, 	"<br>")

	table.sort(Settlements)
	for key, val in pairs(Settlements) do
   		table.insert( frameTable, "{{s|[[" .. val)
   		if string.match(val, "%(") then table.insert( frameTable, "|" .. string.match(val, "([^\(]+) *%(")) end
   		table.insert( frameTable, "]]}}{{•}}")
	end	
	frameTable[#frameTable] = string.gsub( frameTable[#frameTable], "}}{{•}}$", "}}") 

	table.insert( frameTable, "}}")
	frameStr=table.concat(frameTable)

	return frame:preprocess( frameStr ) 
end

return p