Документация
--[[
------------------------------------------
--             AutoDescriptionTeleserial/DonSimon
-- Модуль для заполнения телесериалов. 
------------------------------------------
--]]

local Dates = require("Module:Dates")
local Declension = require("Module:Declension")
local Langs = require("Module:Langs")
local MathTonumber = require("Module:Math/tonumber")
local ReturnGendered = require("Module:ReturnGendered")
local SerializeTable = require("Module:SerializeTable")
local Math = require("Module:Math")
local Country2Adj = require("Module:Country2Adj")

local AutoDescriptionTeleserial={}

-- Формируем и возвращаем три переменных
local description = "" -- строка описания
local details = "" -- уточнение
local categories = "[[Категория:Телесериалы по алфавиту]]" -- категории-- Промежуточный масив сущностей, в который помещаются результаты парсинга перед формированием описания

local entitiesArray = {crt={}, drct={}, genre={}, instanceOf={}, lngT="", member={}, orignCNT={}, role={}, scnW={}, title=""}
local entitiesArrayP = {P31="", P57="", P58="", P136="", P144="", P161="", P170="", P495="", P577="", P1476=""}


-- Точка входа
function AutoDescriptionTeleserial.launch(entity)
 AutoDescriptionTeleserial.parsing(entity) -- парсим карточку викиданных
 AutoDescriptionTeleserial.forming() -- формируем переменные
 return details, description, categories
end	

-- Последовательно проходим свойства в карточке викиданных, для формирования массива сущностей entitiesArray
function AutoDescriptionTeleserial.parsing(entity)
	entitiesArrayP["P31"] = AutoDescriptionTeleserial.parseP31(entity)
	entitiesArrayP["P57"] = AutoDescriptionTeleserial.parseP57(entity)
	entitiesArrayP["P58"] = AutoDescriptionTeleserial.parseP58(entity)
	entitiesArrayP["P136"] = AutoDescriptionTeleserial.parseP136(entity)
	entitiesArrayP["P144"] = AutoDescriptionTeleserial.parseP144(entity)
	entitiesArrayP["P161"] = AutoDescriptionTeleserial.parseP161(entity)
	entitiesArrayP["P170"] = AutoDescriptionTeleserial.parseP170(entity)
	entitiesArrayP["P495"] = AutoDescriptionTeleserial.parseP495(entity)
	entitiesArrayP["P577"] = AutoDescriptionTeleserial.parseP577(entity)
	entitiesArrayP["P1476"] = AutoDescriptionTeleserial.parseP1476(entity)
end

function AutoDescriptionTeleserial.forming()
	
	if(entitiesArrayP["P1476"] ~= "") then
		if(entitiesArray["lngT"] ~= "") then  details = details .. "(" .. Langs.launch(entitiesArray.lngT, entitiesArray.title) .. ")"
		else details = details .. "(" .. entitiesArray.title .. ")" end
	end
	
	
	if(entitiesArrayP["P495"] ~= "") then  
		if(entitiesArrayP["P495"] == "full") then
			if(Country2Adj.launch(entitiesArray.orignCNT[1]) ~= nil and Country2Adj.launch(entitiesArray.orignCNT[2]) ~= nil and entitiesArray.orignCNT[3] == nil) then 
				description = description .. Country2Adj.launch(entitiesArray.orignCNT[1]) .. " и " .. Country2Adj.launch(entitiesArray.orignCNT[2]) .. " "
			else	
				local cnt_adj
				for k, v in pairs (entitiesArray.orignCNT) do
					cnt_adj = Country2Adj.launch(v)
					if(cnt_adj ~= nil) then description = description .. cnt_adj .. ", " 
					else categories = categories .. "[[Категория:Страны без прилагательного]]" end 	
				end	
				description = description:sub(1, #description - 2) .. " "
			end
		else 
			local cnt_adj = Country2Adj.launch(entitiesArrayP.P495)
			if(cnt_adj ~= nil) then description = description .. cnt_adj .. " " 
			else categories = categories .. "[[Категория:Страны без прилагательного]]" end
		end	
	end

	if(entitiesArrayP["P31"] == "телесериал") then description = description .. "[[Телесериалы|телесериал]]." 
	else 
		for ki, vi in pairs (entitiesArray["instanceOf"]) do
			description = description .. "[[" .. vi .. "]], "
		end	
		description=description:sub(1, #description - 2)
	end	 
	
	if(entitiesArrayP["P136"] == "full") then
		if(entitiesArray["genre"][2] == nil) then 
			description = description .. " Жанр: [[" .. entitiesArray.genre[1] .. "]]."
			categories = categories .. "[[Категория:Телесериалы в жанре "..entitiesArray.genre[1].."]]"
		else
			description = description .. " Жанры: " 
			for k, v in pairs (entitiesArray.genre) do
				description = description .. "[[" .. v.. "]]" .. ", "
				categories = categories .. "[[Категория:Телесериалы в жанре "..v.."]]"
			end	
			description=description:sub(1, #description - 2)
        	description=description..". " 
		end	
	end	
	
	if(entitiesArrayP["P170"] == "full") then
		if(entitiesArray["crt"][2] == nil) then description = description .. " Создатель: [[" .. entitiesArray["crt"][1] .. "]]."
		else
			description = description .. " Создатели: " 
			for k, v in pairs (entitiesArray.crt) do
				description = description .. "[[" .. v.. "]]" .. ", "
			end	
			description=description:sub(1, #description - 2)
        	description=description..". " 
		end	
	end	
	if(entitiesArrayP["P57"] == "full") then
		if(entitiesArray["drct"][2] == nil) then description = description .. " Режиссёр: [[" .. entitiesArray["drct"][1] .. "]]."
		else
			description = description .. " Режиссёры: " 
			for k, v in pairs (entitiesArray.drct) do
				description = description .. "[[" .. v.. "]]" .. ", "
			end	
			description=description:sub(1, #description - 2)
        	description=description..". " 
		end	
	end	
	if(entitiesArrayP["P58"] == "full") then
		if(entitiesArray["scnW"][2] == nil) then description = description .. " Сценарист: [[" .. entitiesArray["scnW"][1] .. "]]."
		else
			description = description .. " Сценаристы: " 
			for k, v in pairs (entitiesArray.scnW) do
				description = description .. "[[" .. v.. "]]" .. ", "
			end	
			description=description:sub(1, #description - 2)
        	description=description..". " 
		end	
	end	
	if(entitiesArrayP["P161"] == "full") then
		description = description .. " Актёрский состав: "
     	for k, v in pairs (entitiesArray.member) do
     		if(v ~= " ") then 
     			if (entitiesArray["role"][k] ~= " ") then description = description ..  v .. ' (в роли [[' .. entitiesArray.role[k] .. ']])' .. ", "
     			else description = description ..  v .. ", " end
     		end	
     	end	
        description=description:sub(1, #description - 2)
        description=description..". " 
	end	
	
	if(entitiesArrayP["P144"] ~= "") then description = description .. " Основано на «[[" .. entitiesArrayP.P144 .. "]]»." end
	
	if(entitiesArrayP["P577"] ~= "") then 
		local data = entitiesArrayP.P577
		description = description .. " Дата выхода: "
		if (#data > 4) then
			description = description .. "[[" .. data .. " года]]." 
		else
			description = description .. "[[" .. data .. " год]]." 
		end
		
		local year = data:sub(#data - 4, #data)
		categories = categories .. "[[Категория:Телесериалы"..year.." года".."]]"
		
	end 
	
	if(entitiesArrayP["P495"] ~= "" and entitiesArrayP["P495"] ~= "full") then  
		local dec = Declension.declineWord(entitiesArrayP.P495, 6)
		if(dec ~= "Logical error Declension.declineWord(arg): word not found") then categories = categories .. "[[Категория:Телесериалы в "..dec.."]]"
		else categories = categories .. "[[Категория:Телесериалы в "..entitiesArrayP.P495.."]]"
		end	
	end
	
end


function AutoDescriptionTeleserial.parseP31(entity)
 local p31Statements=mw.wikibase.getAllStatements(entity:getId(), 'P31' ) 
 local i=0
 if(p31Statements ~= "") then
 	for ki, vi in pairs (p31Statements) do
 		if((vi['mainsnak'] ~= nil)) then 
 			local state=mw.wikibase.getLabel(vi['mainsnak']['datavalue']['value']['id'])
 			if (state ~= "") then
 				i=i+1
 				entitiesArray.instanceOf[i]=state
 			end	
 		end
 	end	
 	if(i>0) then return "full"
 	else return "телесериал" end	
 end
end	 

function AutoDescriptionTeleserial.parseP57(entity)
 local p57Statements=entity:getAllStatements("P57")
 local i=1
 for ki, vi in pairs (p57Statements) do
 	if(vi['mainsnak'] ~= nil) then
 		entitiesArray['drct'][i]=mw.wikibase.getLabel(vi['mainsnak']['datavalue']['value']['id'])
 		i = i + 1
 	end	
 end	
 if(i > 1) then return "full"
 else return "" end	
end	

function AutoDescriptionTeleserial.parseP58(entity)
 local p58Statements=entity:getAllStatements("P58")
 local i=1
 for ki, vi in pairs (p58Statements) do
 	if(vi['mainsnak'] ~= nil) then
 		entitiesArray['scnW'][i]=mw.wikibase.getLabel(vi['mainsnak']['datavalue']['value']['id'])
 		i = i + 1
 	end	
 end	
 if(i > 1) then return "full"
 else return "" end	
end	

function AutoDescriptionTeleserial.parseP136(entity)
 local p136Statements=entity:getAllStatements("P136")
 local i=1
 for ki, vi in pairs (p136Statements) do
 	if(vi['mainsnak'] ~= nil) then
 		entitiesArray['genre'][i]=mw.wikibase.getLabel(vi['mainsnak']['datavalue']['value']['id'])
 		i = i + 1
 	end	
 end	
 if(i > 1) then return "full"
 else return "" end	
end	

function AutoDescriptionTeleserial.parseP144(entity)
 local value = entity:formatPropertyValues("P144", mw.wikibase.entity.claimRanks).value
 if(value ~= "") then return value 
 else return ""	end
end	

function AutoDescriptionTeleserial.parseP161(entity)
 local p161Statements=mw.wikibase.getBestStatements(entity:getId(), 'P161' )
 local i=1
 for ki, vi in pairs (p161Statements) do
  	local castMember = ""
  	local charRole = ""
  	if(vi['qualifiers'] ~= nil) then
  		if(vi['qualifiers']['P453'] ~= nil) then charRole = vi['qualifiers']['P453'][1]['datavalue']['value']['id'] end	
  		if(vi['mainsnak'] ~= nil) then castMember = vi['mainsnak']['datavalue']['value']['id'] end
     	if (charRole ~= "") then entitiesArray["role"][i] = mw.wikibase.getLabel(charRole) 
     	else entitiesArray["charRole"][i] = " " end
     	if (castMember ~= "") then entitiesArray["member"][i] = mw.wikibase.getLabel(castMember)
     	else entitiesArray["castMember"][i] = " "	end
  		i=i+1
  	end	
 end	
 if (i>1) then return "full" 
 else return "" end 
end	

function AutoDescriptionTeleserial.parseP170(entity)
 local p170Statements=entity:getAllStatements("P170")
 local i=1
 for ki, vi in pairs (p170Statements) do
 	if(vi['mainsnak'] ~= nil) then
 		entitiesArray['crt'][i]=mw.wikibase.getLabel(vi['mainsnak']['datavalue']['value']['id'])
 		i = i + 1
 	end	
 end	
 if(i > 1) then return "full"
 else return "" end	
end	

function AutoDescriptionTeleserial.parseP495(entity)
 local value = entity:formatPropertyValues("P495", mw.wikibase.entity.claimRanks).value
 if(value ~= "") then 
 	if(string.find(value, ",")) then 
 		local i = 1
 		local p495Statements=entity:getAllStatements("P495")
		for ki, vi in pairs (p495Statements) do
			if(vi['mainsnak'] ~= nil) then
				local label = mw.wikibase.getLabel(vi['mainsnak']['datavalue']['value']['id'])
				if(label ~= "") then entitiesArray.orignCNT[i] = label 
				else entitiesArray.orignCNT[i] = "" end
				i = i + 1
			end	
		end	
 		return "full"
 	else return value end
 else return ""	end
end	

function AutoDescriptionTeleserial.parseP577(entity)
 local value = entity:formatPropertyValues("P577", mw.wikibase.entity.claimRanks).value
 if(value ~= "") then return value 
 else return ""	end
end	

function AutoDescriptionTeleserial.parseP1476(entity)
 local p1476Statements = entity:getAllStatements("P1476")
 for ki, vi in pairs (p1476Statements) do
 	if(vi['mainsnak'] ~= nil) then 
 		if(vi['mainsnak']['datavalue']['value']['language'] ~= nil) then entitiesArray.lngT = vi['mainsnak']['datavalue']['value']['language']
 		else entitiesArray.lngT = " " end	
 		entitiesArray.title = vi['mainsnak']['datavalue']['value']['text']
 		return "full"
 	end	
 end
 return ""	 
end	


return AutoDescriptionTeleserial