{{i}} Документація модуля[створити]
local p = {}

require("Модуль:Функції для карток")

function house_isnotset(args, indx)
	ind_n = ind(indx);
	return ie(args["діаграма"..ind_n]) and ie(args["кількість_депутатів"..ind_n]) and 
	  ie(args["політичні_групи"..ind_n]) and ie(args["голова"..indx]) and 
	  ie(args["останні_вибори"..indx]) and ie(args["заголовок_палати"..indx]);
end

function structure_section(h_item)
	new_args = {};
	if(h_item:getBestStatements('P18')[1] and args["тип"]=="[[двопалатний парламент]]") then
		new_args["діаграма"] = h_item:getBestStatements('P18')[1].mainsnak.datavalue.value; end
	if(h_item:getBestStatements('P1342')[1]) then
		new_args["кількість_депутатів"] = 
		  h_item:getBestStatements('P1342')[1].mainsnak.datavalue.value.amount;
		new_args["кількість_депутатів"] = string.gsub(new_args["кількість_депутатів"], "+", "");
	end
	if(h_item:getBestStatements('P488')[1]) then
		head_id = h_item:getBestStatements('P488')[1].mainsnak.datavalue.value.id;
		new_args["голова"] = title_for(head_id);
		head_item = mw.wikibase.getEntity(head_id);
		if(head_item:getBestStatements('P102')[1]) then
			new_args["партія_голови"] = title_for(head_item:getBestStatements('P102')[1].mainsnak.datavalue.value.id);
		end
	end
	return new_args;
end

function election_section(i)
	res_str = "";
	if(not ie(args["скликання"..i]) and args["тип"]=="[[двопалатний парламент]]") then 
		res_str = res_str..caption.."<small>Скликання:</small>"..cell..args["скликання"..i]; end
	if(not ie(args["останні_вибори"..i])) then 
		res_str = res_str..caption.."<small>Останні вибори:</small>"..cell..args["останні_вибори"..i]; end
	if(not ie(args["наступні_вибори"..i])) then 
		res_str = res_str..caption.."<small>Наступні вибори:</small>"..cell..args["наступні_вибори"..i]; end
	if(not ie(args["виборча_система"..i])) then 
		res_str = res_str..caption.."<small>Виборча система:</small>"..cell..args["виборча_система"..i]; end
	if(not ie(args["термін"..i])) then 
		if(not string.match(args["термін"..i], "%D")) then args["термін"..i] = args["термін"..i].." {{plural:"..args["термін"..i].."|рік|роки|років}}"; end
		res_str = res_str..caption.."Термін:"..cell..args["термін"..i]; end
	return res_str;
end



--головна функція
function p.main(frame)
	parent = frame:getParent();
	args = parent.args;
	
	--перенаправлення старих назв параметрів на нові
	old_to_new_names = 
	{
		{"назва", "name"}, {"герб", "coa_pic"}, {"розмір_герба", "coa_res"}, 
		{"тип", "house_type"}, {"палати", "houses"}, {"держава", "entity"}, 
		{"оригінальна_назва", "native_name"}, {"мова_оригіналу", "native_name_lang"}, 
		{"дата_заснування", "established"}, {"дата_ліквідації", "disestablished"}, 
		{"попередник", "before"}, {"наступник", "after"}, 
		{"діаграма", "structure1"}, {"розмір_діаграми", "structure1_res"}, 
		{"кількість_депутатів", "members"}, {"політичні_групи", "p_groups"}, 
		{"останні_вибори", "last_election"}, {"адреса", "meeting_place"}, 
		{"рік_заснування", "year"}, {"сайт", "website"},
		{"назва_голови1", "leader1_type"}, {"назва_голови2", "leader2_type"}, 
		{"назва_голови3", "leader3_type"}, {"назва_голови4", "leader4_type"}, 
		{"назва_голови5", "leader5_type"}, 
		{"зображення", "session_room"}, {"розмір_зображення", "session_res"}, 
		{"зображення2", "session_room2"}, {"розмір_зображення2", "session_res2"}, 
		{"держава", "юрисдикція"}
	};
	old_to_new_names_indexed = 
	{{"голова", "leader"}, {"партія_голови", "party"}, {"дата_обрання_голови", "election"}};

	i = 1;
	while(i<=(#old_to_new_names)) do
		if(ie(args[old_to_new_names[i][1]]) and not ie(args[old_to_new_names[i][2]])) 
			then args[old_to_new_names[i][1]] = args[old_to_new_names[i][2]]; end
		i = i+1;
	end

	j = 1;
	while(j<=5) do
		i = 1;
		while(i<=(#old_to_new_names_indexed)) do
			if(ie(args[old_to_new_names_indexed[i][1]..j]) and not ie(args[old_to_new_names_indexed[i][2]..j])) 
				then args[old_to_new_names_indexed[i][1]..j] = args[old_to_new_names_indexed[i][2]..j]; end
			i = i+1;
		end
		j = j+1;
	end
	
	--якщо не задані значення деяких параметрів, беремо значення із Вікіданних
	element = mw.wikibase.getEntityIdForCurrentPage();
	if(not element and not ie(args["елемент"])) then element = args["елемент"]; end
	item = mw.wikibase.getEntity(element);
	
	if(ie(args["назва"])) then args["назва"] = mw.text.split(mw.title.getCurrentTitle().text, " %(")[1]; end
	
	if(ie(args["оригінальна_назва"]) and item and item:getBestStatements('P1705')[1] and 
	  item:getBestStatements('P1705')[1].mainsnak.datavalue.value.language~="uk") then
		args["оригінальна_назва"] = item:getBestStatements('P1705')[1].mainsnak.datavalue.value.text;
		args["мова_оригіналу"] = item:getBestStatements('P1705')[1].mainsnak.datavalue.value.language;
	end
	
	--зображення
	if(ie(args["герб"]) and item) then 
		if(item:getBestStatements('P154')[1]) then
			args["герб"] = item:getBestStatements('P154')[1].mainsnak.datavalue.value;
		elseif(item:getBestStatements('P158')[1]) then
			args["герб"] = item:getBestStatements('P158')[1].mainsnak.datavalue.value;
		elseif(item:getBestStatements('P94')[1]) then
			args["герб"] = item:getBestStatements('P94')[1].mainsnak.datavalue.value;
		else
			country_element = item:getBestStatements('P17')[1];
			if(country_element) then
				country_item = mw.wikibase.getEntity(country_element.mainsnak.datavalue.value.id);
				if(country_item:getBestStatements('P94')[1]) then
					args["герб"] = country_item:getBestStatements('P94')[1].mainsnak.datavalue.value;
				end
			end
		end
	end
	
	if(ie(args["зображення"]) and item and item:getBestStatements('P18')[1]) then
		args["зображення"] = item:getBestStatements('P18')[1].mainsnak.datavalue.value; end
	
	--основна інформація
	if(ie(args["держава"]) and item and item:getBestStatements('P17')[1]) then
		args["держава"] = title_for(item:getBestStatements('P17')[1].mainsnak.datavalue.value.id, true);
	end
	if(ie(args["держава"])) then args["держава"] = " "; end
	
	if(ie(args["тип"]) and item) then 
		parl_type = item:getBestStatements('P31')[1].mainsnak.datavalue.value.id;
		if(parl_type=="Q37002670") then args["тип"] = "[[однопалатний парламент]]";
		elseif(parl_type=="Q189445") then args["тип"] = "[[двопалатний парламент]]";
		elseif(parl_type=="Q637846") then args["тип"] = "[[верхня палата]]";
		elseif(parl_type=="Q375928") then args["тип"] = "[[нижня палата]]";
		else end
	else
		args["тип"] = string.lower(args["тип"]);
		if(args["тип"]=="однопалатний" or args["тип"]=="двопалатний") then
			args["тип"] = "[["..args["тип"].." парламент]]";
		elseif(args["тип"]=="верхня" or args["тип"]=="нижня") then
			args["тип"] = "[["..args["тип"].." палата]]";
		else end
	end

	if((args["тип"]=="[[верхня палата]]" or args["тип"]=="[[нижня палата]]") and 
	  ie(args["частина_від"]) and item:getBestStatements('P361')[1]) then
		args["частина_від"] = title_for(item:getBestStatements('P361')[1].mainsnak.datavalue.value.id);
	end
	
	if(ie(args["палати"]) and item and item:getBestStatements('P527')[2]) then
		args["палати"] = title_for(item:getBestStatements('P527')[1].mainsnak.datavalue.value.id)..
		  "<br/>"..title_for(item:getBestStatements('P527')[2].mainsnak.datavalue.value.id);
	end
	
	if(ie(args["дата_заснування"]) and item and item:getBestStatements('P571')[1]) then
		value = item:getBestStatements('P571')[1].mainsnak.datavalue.value;
		args["дата_заснування"] = format_time(value);
		args["рік_заснування"] = string.sub(value.time, 2, 5);
	end
	
	if(ie(args["дата_ліквідації"]) and item and item:getBestStatements('P576')[1]) then
		args["дата_ліквідації"] = format_time(item:getBestStatements('P576')[1].mainsnak.datavalue.value);
	end
	
	if(ie(args["попередник"]) and item and item.claims) then
		if(item:getBestStatements('P155')[1]) then
			args["попередник"] = title_for(item:getBestStatements('P155')[1].mainsnak.datavalue.value.id);
		elseif(item:getBestStatements('P1365')[1]) then
			args["попередник"] = title_for(item:getBestStatements('P1365')[1].mainsnak.datavalue.value.id);
		else end
	end
	
	if(ie(args["наступник"]) and item and item:getBestStatements('P156')[1]) then
		args["наступник"] = title_for(item:getBestStatements('P156')[1].mainsnak.datavalue.value.id); end
	
	--структура/інформація про палати
	if(args["тип"]=="[[двопалатний парламент]]" and item) then
		if(item:getBestStatements('P527')[2] and house_isnotset(args, "1") and house_isnotset(args, "2")) then
			id1 = item:getBestStatements('P527')[1].mainsnak.datavalue.value.id;
			 new_args = structure_section(mw.wikibase.getEntity(id1));
			 for k,v in pairs(new_args) do args[k.."1"] = v; end
			 if(ie(args["заголовок_палати"])) then args["заголовок_палати"] = title_for(id1); end
			id2 = item:getBestStatements('P527')[2].mainsnak.datavalue.value.id;
			 new_args = structure_section(mw.wikibase.getEntity(id2));
			 for k,v in pairs(new_args) do args[k.."2"] = v; end
			 if(ie(args["заголовок_палати2"])) then args["заголовок_палати2"] = title_for(id2); end
		end
	else
		if(house_isnotset(args, "1") and item) then
			new_args = structure_section(item);
			for k,v in pairs(new_args) do args[k.."1"] = v; end
		end
	end
	
	if(ie(args["заголовок_палати"])) then args["заголовок_палати"] = "Структура"; end
	
	--адреса
	if(ie(args["адреса"]) and item) then 
		if(item:getBestStatements('P6375')[1]) then
			args["адреса"] = item:getBestStatements('P6375')[1].mainsnak.datavalue.value;
		elseif(item:getBestStatements('P159')[1]) then
			args["адреса"] = title_for(item:getBestStatements('P159')[1].mainsnak.datavalue.value.id);
			if(item:getBestStatements('P159')[1].qualifiers) then
				if(item:getBestStatements('P159')[1].qualifiers.P281) then
					args["адреса"] = args["адреса"]..", "..
					  item:getBestStatements('P159')[1].qualifiers.P281[1].datavalue.value;
				end
				if(item:getBestStatements('P159')[1].qualifiers.P669) then
					args["адреса"] = args["адреса"]..", "..
					  title_for(item:getBestStatements('P159')[1].qualifiers.P669[1].datavalue.value.id);
				end
				if(item:getBestStatements('P159')[1].qualifiers.P670) then
					args["адреса"] = args["адреса"]..", "..
					  item:getBestStatements('P159')[1].qualifiers.P670[1].datavalue.value;
				end
			end
		else end
	end
	
	if(ie(args["сайт"]) and item and item:getBestStatements('P856')[1]) then
		args["сайт"] = item:getBestStatements('P856')[1].mainsnak.datavalue.value;
		args["сайт"] = string.gsub(args["сайт"], "http://", "");
		args["сайт"] = string.gsub(args["сайт"], "https://", "");
		if(string.sub(args["сайт"], -1, -1)=="/") then
			args["сайт"] = string.sub(args["сайт"], 1, -2); end
	end
	
	if(ie(args["вікісховище"]) and item and item:getBestStatements('P373')[1]) then
		args["вікісховище"] = item:getBestStatements('P373')[1].mainsnak.datavalue.value; end
	
	for k,v in pairs(args) do 
		if(v=="-" or v=="—") then args[k]=""; end
	end	



	--конструюємо текст, що має бути повернений
	default_image_width = "250x170px";
	default_small_image_width = "125x125px"
	section_header = "\n|-\n| style='background:#cde; text-align:center; font-weight:bold' colspan='2' | ";
	two_columns_cell = "\n|-\n| style='text-align:center' colspan='2' | ";
	caption = "\n|-\n| style='text-align:right; background:#eee; width:40%; font-weight:bold' | ";
	cell = "\n| ";
	res = {'{| class="infobox" style="width:300px; font-size:90%"', 
		'\n|- style="font-size:120%; text-align:center; background:#cde"', 
		'\n| colspan="2"| ', "'''", args["назва"], "'''"};
	
	i = 1;
	while(not ie(args["оригінальна_назва"..ind(i)]) and not ie(args["мова_оригіналу"..ind(i)])) do
		table.insert(res, '<br/>{{lang-'..args["мова_оригіналу"..ind(i)]..
		  '|'..args["оригінальна_назва"..ind(i)]..'}}');
		i = i+1;
	end
	
	if(not ie(args["скликання"]) and args["тип"]~="двопалатний парламент") then
		if(not string.match(args["скликання"], "%D"))
			then args["скликання"] = args["скликання"].." скликання"; end
		table.insert(res, two_columns_cell..args["скликання"]);
	end
	
	--герби
	if(not ie(args["герб2"]) and not ie(args["герби_горизонтально"])) then
		if(ie(args["розмір_герба"])) then args["розмір_герба"] = default_small_image_width; end
		if(ie(args["розмір_герба2"])) then args["розмір_герба2"] = default_small_image_width; end
		table.insert(res, two_columns_cell..'<table width="100%"><tr><td>[[Файл:'..args["герб"]..'|'..args["розмір_герба"]..
		  ']]<td>[[Файл:'..args["герб2"]..'|'..args["розмір_герба2"]..
		  ']]<tr><td>'..args["підпис_герба"]..'<td>'..args["підпис_герба2"]..'</table>');
	else
		if(not ie(args["герб"])) then
			if(ie(args["розмір_герба"])) then args["розмір_герба"] = default_image_width; end
			if(ie(args["підпис_герба"])) then args["підпис_герба"] = "&nbsp;"; end
			table.insert(res, two_columns_cell..'[[Файл:'..args["герб"]..'|'..args["розмір_герба"]..']]'..
			  two_columns_cell..args["підпис_герба"]);
		end
		if(not ie(args["герб2"])) then
			if(ie(args["розмір_герба2"])) then args["розмір_герба2"] = default_image_width; end
			if(ie(args["підпис_герба2"])) then args["підпис_герба2"] = "&nbsp;"; end
			table.insert(res, two_columns_cell..'[[Файл:'..args["герб2"]..'|'..args["розмір_герба2"]..']]'..
			  two_columns_cell..args["підпис_герба2"]);
		end
	end
	
	--зображення
	i = 1;
	while(not ie(args["зображення"..ind(i)])) do
		index = ind(i);
		if(ie(args["розмір_зображення"..index])) then args["розмір_зображення"..index] = default_image_width; end
		if(ie(args["підпис_зображення"..index])) then args["підпис_зображення"..index] = "&nbsp;"; end
		table.insert(res, two_columns_cell..'[[Файл:'..args["зображення"..index]..
		  '|'..args["розмір_зображення"..index]..']]'..
		  two_columns_cell..args["підпис_зображення"..index]);
		i = i+1;
	end
	
	--основна інформація
	if(not ie(args["держава"]) or not ie(args["тип"]) or not ie(args["палати"]) or 
	  not ie(args["дата_заснування"]) or not ie(args["дата_ліквідації"]) or 
	  not ie(args["попередник"]) or not ie(args["наступник"])) then
		table.insert(res, section_header.."Загальна інформація:");
	end
	
	if(not ie(args["держава"])) then table.insert(res, caption.."Юрисдикція:"..cell..args["держава"].."\n"); end
	if(not ie(args["тип"])) then table.insert(res, caption.."Тип:"..cell..args["тип"].."\n"); end
	if(not ie(args["частина_від"])) then table.insert(res, caption.."Частина від:"..cell..args["частина_від"].."\n"); end
	if(not ie(args["палати"])) then table.insert(res, caption.."Палати:"..cell..args["палати"].."\n"); end
	if(not ie(args["дата_заснування"])) then 
		table.insert(res, caption.."<small>Дата заснування:</small>"..cell..args["дата_заснування"].."\n"); end
	if(not ie(args["дата_ліквідації"])) then 
		table.insert(res, caption.."<small>Дата ліквідації:</small>"..cell..args["дата_ліквідації"].."\n"); end
	if(not ie(args["попередник"])) then table.insert(res, caption.."Попередник:"..cell..args["попередник"].."\n"); end
	if(not ie(args["наступник"])) then table.insert(res, caption.."Наступник:"..cell..args["наступник"].."\n"); end
	
	--структура/інформація про палати
	i = 1;
	while(not house_isnotset(args, tostring(i))) do
		index = ind(i);
		if(not ie(args["заголовок_палати"..index])) then
			table.insert(res, section_header..args["заголовок_палати"..index]..":\n"); end
		if(not ie(args["діаграма"..index])) then
			if(ie(args["розмір_діаграми"..index])) then 
				args["розмір_діаграми"..index] = default_image_width; end
			table.insert(res, two_columns_cell..'[[Файл:'..args["діаграма"..index]..
			  '|'..args["розмір_діаграми"..index]..']]\n'); end
		if(not ie(args["кількість_депутатів"..index])) then 
			table.insert(res, caption.."Депутатів:"..cell..args["кількість_депутатів"..index].."\n"); end
		if(not ie(args["політичні_групи"..index])) then 
			if(not ie(args["згорнути_групи"..index])) then collapse_start = '{{Hidden|&nbsp;|2='; collapse_end = '}}';
			else collapse_start = ''; collapse_end = ''; end
			table.insert(res, caption.."Політичні<br/>групи:"..cell..collapse_start..args["політичні_групи"..index]..collapse_end.."\n"); end

		j = 1;
		index_head = i;
		while(not ie(args["голова"..index_head])) do
			if(ie(args["назва_голови"..index_head])) then 
				 if(j==1) then args["назва_голови"..index_head] = "Спікер";
				 else args["назва_голови"..index_head] = "Віце-спікер"; end
			end
			table.insert(res, caption..args["назва_голови"..index_head]..":"..cell..args["голова"..index_head]);
			if(not ie(args["партія_голови"..index_head])) then
				table.insert(res, " ("..args["партія_голови"..index_head]..")"); end
			if(not ie(args["дата_обрання_голови"..index_head])) then
				table.insert(res, "<br/>з "..args["дата_обрання_голови"..index_head]); end
			j = j+1; index_head = i.."_"..j;
		end

		table.insert(res, election_section(i));
		i = i+1;
	end
	
	--виборча система
	if(not ie(args["останні_вибори"]) or not ie(args["наступні_вибори"]) or 
	  not ie(args["виборча_система"]) or not ie(args["термін"]) or 
	  (not ie(args["скликання"] and args["тип"]=="двопалатний парламент")) ) then
		table.insert(res, section_header.."Вибори:"..election_section(""));
	end
	
	--інше
	if(not ie(args["мітка1"]) and not ie(args["текст1"])) then
		table.insert(res, section_header.."Інше:\n"..caption..args["мітка1"]..cell..args["текст1"]..'\n'); end
	x = 2;
	while(not ie(args["мітка"..x]) and not ie(args["текст"..x])) do
		table.insert(res, caption..args["мітка"..x]..cell..args["текст"..x]..'\n');
		x = x+1;
	end
	
	--адреса
	if(not ie(args["адреса"])) then table.insert(res, section_header.."Адреса:"); end
	
	if(ie(args["no_mapframe"])) then
		if (ie(args["mapframe_широта"]) or ie(args["mapframe_довгота"])) and item.claims and item.claims['P159'] then
			headquarters_id = item:getBestStatements('P159')[1].mainsnak.datavalue.value.id
			headquarters_item = mw.wikibase.getEntity(headquarters_id)
			headquarters_coords = headquarters_item:getBestStatements('P625')[1].mainsnak.datavalue.value
			args["mapframe_широта"] = headquarters_coords.latitude
			args["mapframe_довгота"] = headquarters_coords.longitude
		end
		table.insert(res, two_columns_cell..
		  '{{Mapframe маркер розташування'..'|ширина=270|висота=200'..
		  '|масштаб='..ternary(ie(args["mapframe_масштаб"]), "", args["mapframe_масштаб"])..
		  '|широта='..ternary(ie(args["mapframe_широта"]), "", args["mapframe_широта"])..
		  '|довгота='..ternary(ie(args["mapframe_довгота"]), "", args["mapframe_довгота"])..
		  '|назва='..ternary(ie(args["mapframe_назва"]), args["назва"], args["mapframe_назва"])..
		  '|маркер='..ternary(ie(args["mapframe_маркер"]), "town-hall", args["mapframe_маркер"])..
		  '|колір='..ternary(ie(args["mapframe_колір"]), '#777', args["mapframe_колір"])..
		  '}}\n');
	end
	
	if(not ie(args["адреса"])) then table.insert(res, caption.."Адреса:"..cell..args["адреса"]..'\n'); end
	
	--сайт
	if(not ie(args["сайт"])) then
		table.insert(res, section_header.."Офіційний вебсайт:"..two_columns_cell..
		  "[http://"..args["сайт"].." "..args["сайт"].."]");
	end
	i = 2;
	while(not ie(args["сайт"..i])) do
		table.insert(res, "<br/>[http://"..args["сайт"..i].." "..args["сайт"..i].."]");
		i = i+1;
	end
	table.insert(res, "\n");
	
	--посилання на вікісховище
	if(not ie(args["вікісховище"])) then
		if(ie(args["вікісховище_назва"])) then args["вікісховище_назва"] = args["назва"]; end
		table.insert(res, two_columns_cell.."<hr>"..two_columns_cell..
		  '<table cellspacing=10><tr><td width=0%>[[File:Commons-logo.svg|30px]]'..
		  '<td align=left>[[Вікісховище]] має мультимедійні дані за темою: '..
		  "'''[[:commons:Category:"..args["вікісховище"].."|"..args["вікісховище_назва"]..
		  "]]'''</table>\n");
	end
	
	categories = "";
	if(not ie(args["рік_заснування"])) then
		categories = categories..'[[Категорія:Органи влади, засновані '..args["рік_заснування"]..']]\n'; end


	return frame:preprocess(table.concat(res).."|}\n"..categories);
end

return p;