Module:Lok sabha constituency
local loksabha = {}
 local args = {}
 local QId;
 local label =mw.loadData('Module:Lok_sabha_constituency/labels')
 local lang=mw.language.getContentLanguage().code
 
 local function ifnotempty(s,a,b)
 	if (s and s ~= '') then
 		return a
 	else
 		return b
 	end
 end
 
 local function ifexist(page)
     if not page then return false end
     if mw.title.new(page).exists then return true end
     return false
 end
 
 local function getwikidatalabel(id)	
 	--wikidata label
 	return mw.wikibase.label(id) or id
 end
 	
 local function getwikilink(id)
 	if	ifexist(mw.wikibase.sitelink(id)) then
 		return '[['.. mw.wikibase.sitelink(id) .. '|'.. mw.wikibase.label(id) ..']]'
 	else
 		return mw.wikibase.label(id) or id
 	end
 end
 
 --comma
 function comma_value(amount)
 	if amount==nil then return end
   local formatted = tonumber(amount)
   while true do  
     formatted, k = string.gsub(formatted, &quot;^(-?%d+)(%d%d%d)&quot;, '%1,%2')
     if (k==0) then
       break
     end
   end
   return formatted
 end
 
 	--print(getProperty('Q1255973','P159'))
 function getProperty(id, propertyName )
 	local entity = mw.wikibase.getEntityObject(id)
 	return getPropertyByEntity(entity,propertyName);
 
 end --getproperty
 function getPropertyByEntity(_entity, propertyName )
 	local entity = _entity; -- mw.wikibase.getEntityObject(id)
 	if not entity or not entity.claims then return end--the entity doesnt exist or have no claims
 	local property = entity.claims[propertyName]
 	if not property then return end--no such property for this item
 
 	--lang=mw.language.getContentLanguage()
 	i=1
 	default_lang='en'
 	local default_text=''
 	for _ in ipairs(property) do
 
 		propy = property[i]
 		i=i+1
 		local propValue = propy.mainsnak and propy.mainsnak.datavalue
 	 	local propType = propy.mainsnak and propy.mainsnak.datatype
 		if not propValue then return end --property doesnt exist
 	
 	
 		if propValue and propValue['type'] == 'monolingualtext' and propValue.value['language'] == default_lang then
 			default_text = propValue.value['text']..mw.ustring.format( &quot;update at :[[:wikidata:%s|%s]]&quot;, _entity.id, _entity.id..':'.. propertyName )
 		end
 	
 		if propValue['type'] == 'wikibase-entityid' then
 			local linkTarget = mw.wikibase.sitelink( &quot;Q&quot; .. propValue.value['numeric-id'] )
 			local linkTitle = mw.wikibase.label( &quot;Q&quot; ..propValue.value['numeric-id'] )
 			return linkTarget and linkTitle and mw.ustring.format( &quot;[[%s|%s]]&quot;, linkTarget, linkTitle )
 			--return  linkTitle 
 			
 		elseif propValue and propValue['type'] == 'monolingualtext' and propValue.value['language'] == lang then 
 			return propValue.value['text'] 
 		elseif propType and  (propType  == 'commonsMedia' or propType=='string') then
 			return propValue['value']
 		elseif propType and propType  == 'quantity' then
 			return tonumber(propValue.value['amount'])
 		end --if
 
 	end --for
 
 	return default_text; --incase value for other language missing
 
 end --getproperty
 
 function getQualifierDateValue(_entity,propertyID,qualifierID)
 	local pattern = &quot;+(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z&quot;
 	if _entity.claims[propertyID] ~= nil  then
 		local out = {}
 		for k, v in pairs(_entity.claims[propertyID]) do
 			if v.qualifiers and v.qualifiers[qualifierID] ~= nil  then
 				for k2, v2 in pairs(v.qualifiers[qualifierID]) do
 					if v2.datatype=='time' and  v2.datavalue ~=nill then
 						local xyear=v2.datavalue.value['time']:match(pattern)
 						--print(xyear)
 
 						table.insert(out ,xyear)
 					elseif v2.datatype==&quot;time&quot;  and v2.snaktype==&quot;novalue&quot; then
 
 						table.insert(out, v2.snaktype)
 					end
 				end
 			end
 		end
 		return out
 	else
 		return &quot;&quot;
 	end
 	
 end
 
 function getExistence(_entity)
 	local a={}
 	local b={}
 	a=getQualifierDateValue(_entity,'P31','P580'); --instance of / start time
 	b=getQualifierDateValue(_entity,'P31','P582');--instance of / end time
 
 	table.sort(a)
 	table.sort(b)
 
 	local str=&quot;&quot;;
 
 	if a~=nil then
 		for k,v in ipairs(a) do
 			if str ~=&quot;&quot; then	str= str..&quot;&lt;br&gt;&quot; end
 			if  tonumber(v) and tonumber(b[k]) and tonumber(v)&lt;tonumber(b[k]) then
 				str=tostring(str) .. tostring(v) ..&quot; - &quot;.. tostring(b[k])
 			elseif  tonumber(b[k]) ==nil then
 				if b[k]==&quot;novalue&quot; or b[k]==nil then b[k]= label.Present; end --mw.wikibase.label(&quot;Q193168&quot;) or &quot;[[d:Q193168|]]&quot; end --present
 				str=tostring(str) .. tostring(v) ..&quot; - &quot;.. tostring(b[k])	
 			end
 		end
 	else
 		str=&quot;Start Time Property value &lt;br /&gt;missing at [[d:&quot;.. _entity.id ..&quot;:P31:P580]]&quot;
 	end
 
 	--print(str)
 	return(str)
 end
 
 --print(getPropertyValue('Q7785493','P991'))
 function getPropertyValue(id, propertyName )
 	local _entity = mw.wikibase.getEntityObject(id)
 	
 	return getPropertyValueByEntity(_entity,propertyName)
 
 end --getPropertyValueById
 
 function getPropertyValueByEntity(_entity, propertyName )
 	if not _entity or not _entity.claims then return end--the entity doesnt exist or have no claims
 	local property = _entity.claims[propertyName]
 	if not property then return end--no such property for this item
 
 	--local lang=mw.language.getContentLanguage().code
 	i=1
 	
 	for _ in ipairs(property) do
 
 		propy = property[i]
 		i=i+1
 		local propValue = propy.mainsnak and propy.mainsnak.datavalue
 	 local propType = propy.mainsnak and propy.mainsnak.datatype
 		if not propValue then return end --property doesnt exist
 	
 --	print(mw.dumpObject(propValue))
 		if propValue['type'] == 'wikibase-entityid' then
 			local numericid =  &quot;Q&quot; .. propValue.value['numeric-id']
 			
 			return numericid	
 		elseif propValue and propValue['type'] == 'monolingualtext' and propValue.value['language'] == lang then 
 			return propValue.value['text'] 
 		else
 			return
 		end --if
 
 	end --for
 
 	return default_text; --incase value for other language missing
 
 end --getPropertyValueByEntity
 
 local function getReserved(classification)
 	--local classification=getPropertyValueByEntity(_entity,'P2502') --P2502:classification
 	if classification == nill then return end 
 	classification='Q'..classification
 	local scst=getPropertyValue(classification,'P361') --P361 :partof
 	--print(scst)
 	if	ifexist(mw.wikibase.sitelink(scst)) then
 		_shortname=getShortName(classification);
 		if  _shortname~=nil then --P1813:short name
 			return mw.ustring.format( &quot;[[%s|%s]]&quot;, mw.wikibase.sitelink(scst), mw.wikibase.label(classification))	
 		else
 			return mw.ustring.format( &quot;[[%s]]&quot;, mw.wikibase.sitelink(scst))
 		end	
 	else
 		return mw.wikibase.label(classification) or classification
 	end
 end
 --print(getReserved('22813282'))
 
 function getPartyLink(partyid)--party of successful candidate
 	local str=&quot;Qualifier Political party (102) is missing under P585 in [[d:&quot;.. QId ..&quot;]]&quot;;
 	if partyid==nil then return str end;
 	--local partyid=getPropertyValue(id,'P102')--member of political party
 	partyid='Q'..partyid
 	if	ifexist(mw.wikibase.sitelink(partyid)) then
 		_shortname=getShortName(partyid);
 		if  _shortname~=nil then --short name
 			str= mw.ustring.format( &quot;[[%s|%s]]&quot;, mw.wikibase.sitelink(partyid), _shortname)	
 		else
 			str= mw.ustring.format( &quot;[[%s]]&quot;, mw.wikibase.sitelink(partyid))
 		end	
 	else
 		str= mw.wikibase.label(partyid) or &quot;Political party (P102) is missing at [[d:&quot;.. QId ..&quot;]]&quot;;
 	end
 	
 	return str
 end
 function getCurrentMP(_id)
 	local propertyID =&quot;P991&quot; --successful candidate
 	local str=&quot;Current MP (Successful candidate - P991) name is missing at [[d:&quot;.. QId ..&quot;]]&quot;;
 	if _id==nil then return str;
 		
 	elseif	ifexist(mw.wikibase.sitelink(_id)) then
 		str=mw.ustring.format( &quot;[[%s|%s]]&quot;, mw.wikibase.sitelink(_id), mw.wikibase.label(_id))	
 		
 	elseif mw.wikibase.label(_id) then
 		str= mw.ustring.format( &quot;[[%s]]&quot;, mw.wikibase.label(_id))
 	else
 		str=_id
 	end
 
 	return str;
 end
 
 function getElectionYear(_id,elec_year)
 	if _id==nil or _id=='Q' then 
 		return nil;		
 	elseif	mw.wikibase.sitelink(_id)~=nil then
 		return mw.ustring.format( &quot;[[%s|%s]]&quot;, mw.wikibase.sitelink(_id), elec_year)	
 	elseif mw.wikibase.label(_id) then
 		return mw.ustring.format( &quot;[[%s|%s]]&quot;, mw.wikibase.label(_id), elec_year)	
 	else
 		return nil
 	end	
 end
 
 function getMostSuccessfulParty(_entity)
 
 	party_list={}
 	local propertyID='P585' --point in time	
 	if _entity.claims[propertyID]  then
 		local pattern=&quot;+(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z&quot;
 
 		for k, v in pairs(_entity.claims[propertyID]) do
 			P585Qual = v['qualifiers'];
 			
 			if P585Qual~=nil  and P585Qual['P102']~=nil then S102=P585Qual['P102'][1].datavalue.value['numeric-id']; end --classification
 			local string s=mw.ustring.format(&quot;%s&quot;,S102)
 			if party_list[s] ~=nil then
 				party_list[s]=tonumber(party_list[s])+1;
 			else
 				party_list[s]=1;
 			end
 			
 		end
 	
 	end
 		
 			
 	local max_val, key = -math.huge
 
 
 	for k, v in pairs(party_list) do
 		if v &gt; max_val then
 			max_val, key = v, k
 		end
 	end
 
 	if key~=nil then
 		_shortname=getShortName('Q'..key);
   		if  mw.wikibase.sitelink('Q'..key)~=nil then
 			party=mw.ustring.format(&quot;[[%s|%s]]&quot;, mw.wikibase.sitelink('Q'..key), _shortname or mw.wikibase.label('Q'..key) or '')
 		elseif mw.wikibase.label('Q'..key)~=nil then
 			party=mw.ustring.format(&quot;[[%s]]&quot;, mw.wikibase.label('Q'..key))
 		else
 			party=mw.ustring.format(&quot;[[:d:%s]]&quot;, 'Q'..key)
 		end
 		
 		return mw.ustring.format(&quot;%s \(%s %s\)&quot;,party, max_val,label.Times)
 	else
 		return &quot;&quot;
 	end
 end
 
 function getImage(_entity)
 	local property=getPropertyByEntity(_entity, 'P242' )
 	if  property~=nil then
 		return mw.ustring.format( &quot;[[File:%s|220px]]&quot;, property)	
 	else
 		return ''			
 	end	
 end
 
 function getImageLegend(_entity)
 	
 	--lang=mw.language.getContentLanguage().code
 	
 	local propertyID='P242' --locator map image
 	local qualifierID='P2096' --image legend
 	local legend =&quot;Image Legend qualifier &lt;br /&gt;missing at [[d:&quot;.. _entity.id ..&quot;:P242:P2096]]&quot;;
 	if _entity.claims[propertyID]  then
 		for k, v in pairs(_entity.claims[propertyID]) do
 			if v.qualifiers~=nil and v.qualifiers[qualifierID]  then
 				for k2, v2 in pairs(v.qualifiers[qualifierID]) do
 					if v2.datatype=='monolingualtext' and  v2.datavalue ~=nill and v2.datavalue.value['language']==lang then
 						legend=v2.datavalue.value['text'];
 					end
 				end
 			end
 		end
 	end
 	return legend;
 end
 
 	local function getElectors(_entity)
 		local property=getPropertyByEntity(_entity, 'P1867' )--eligible voters
 		if  property~=nil then
 			return mw.ustring.format( &quot;%s&quot;, property)	
 		else
 			return ''			
 		end
 	end
 	
 	local function assemblylist(_entity)
 		--has part P527
 		--local Qid=&quot;Q7785493&quot;
 		local propertyID =&quot;P527&quot;--has part
 		--local entity = mw.wikibase.getEntityObject(Qid)
 		local str=&quot;&quot;
 		if _entity.claims[propertyID] ~= nil then
 			for k, v in pairs(_entity.claims[propertyID]) do
 				if str ~=&quot;&quot; then	str= str..&quot;&lt;br&gt;&quot; end
 				local id='Q' ..v.mainsnak.datavalue.value['numeric-id']
 				local series=getProperty(id,'P1545')
 				if series~=nil then series=series ..&quot;. &quot; end
 			--	str =str .. (series or '') .. mw.ustring.format( &quot;[[%s|%s]]&quot;, mw.wikibase.sitelink(id), mw.wikibase.label(id))
 				
 				if	mw.wikibase.sitelink(id)~=nil and mw.wikibase.label(id) ~=nil then
 					str =str .. mw.ustring.format( &quot;[[%s|%s]]&quot;, mw.wikibase.sitelink(id), mw.wikibase.label(id))	
 				elseif mw.wikibase.sitelink(id)~=nil then
 					str =str .. mw.ustring.format( &quot;[[%s]]&quot;, mw.wikibase.sitelink(id))
 				elseif mw.wikibase.label(id)~=nil then
 					str =str .. mw.ustring.format( &quot;[[%s]]&quot;, mw.wikibase.label(id))	
 				else
 					str =str .. mw.ustring.format( &quot;[[:d:%s]]&quot;, id)
 				end	
 				
 
 			end
 		--	print(str)
 		end
 		return str;
 		
 	end
 	
 	
 
 	function getShortName(_id)
 		local _entity = mw.wikibase.getEntityObject(_id)
 		if _entity==nil then return ;
 		elseif _entity.claims==nil then return end;
 		local propertyID='P1813'
 		if _entity.claims[propertyID]  then
 			for k, v in pairs(_entity.claims[propertyID]) do
 		--print(mw.dumpObject(v.mainsnak.datavalue.value))
 				if(v.mainsnak.datavalue.value.language==lang)then
 					return v.mainsnak.datavalue.value.text;
 				end
 				
 			end
 		
 		end
 	end
 	local function setarg(k, v)
 		if(v and v ~= '') then args[k] = v end
 	end
 	
 	local function loadLokSabha(frame,s)
 
 		local yearstr = string.sub(s,1,4)
 		local Elected_Year =frame.args.Elected_Year
 		QId=string.sub(s,5) or QId
 		local _entity = mw.wikibase.getEntityObject(QId)
 		local lokassmlist = assemblylist(_entity)
 		local propertyID='P585' --point in time
 		local elec_year
 		if _entity.claims[propertyID]  then
 			local elyear={}
 			local pattern = &quot;+(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z&quot;
 				
 			pos=1
 			for k, v in pairs(_entity.claims[propertyID]) do
 				local val=mw.ustring.format(&quot;%s%s%s&quot;,v.mainsnak.datavalue.value.time:match(pattern))
 				elyear[pos]=val
 				pos=pos+1
 			end
 			
 			local max_val, key = -math.huge
 			
 			for k, v in pairs(elyear) do
 
 				if tonumber(v) &gt; tonumber(max_val) then
 					max_val, key = v, k
 				end
 			end
 			P585Qual = _entity.claims[propertyID][key]['qualifiers']
 			elec_year = string.sub(max_val,1,4)
 			if P585Qual['P2502']~=nil then P2502=P585Qual['P2502'][1].datavalue.value['numeric-id']; end
 			if P585Qual['P102'] ~=nil then P102 =P585Qual['P102'][1].datavalue.value['numeric-id']; end
 			if P585Qual['P805'] ~=nil then P805 ='Q'..P585Qual['P805'][1].datavalue.value['numeric-id']; end
 			if P585Qual['P991'] ~=nil then P991 ='Q'..P585Qual['P991'][1].datavalue.value['numeric-id']; end
 			if P585Qual['P1867'] ~=nil then P1867 =P585Qual['P1867'][1].datavalue.value['amount']; end
 			if P585Qual['P1868'] ~=nil then P1868 =P585Qual['P1868'][1].datavalue.value['amount']; end
 		end
 		
 		setarg('title',getwikidatalabel(QId))
 		setarg('image',  getImage(_entity) )
 		setarg('caption',  getImageLegend(_entity) or '')
 		setarg('Existence',  getExistence(_entity) or '')
 		setarg('Reservation',  getReserved(P2502) or'')
 		setarg('CurrMP', getCurrentMP(P991))
 		setarg('Party', getPartyLink(P102))
 		setarg('Yr', getElectionYear(P805, elec_year) or Elected_Year or '')
 		setarg('State', getPropertyByEntity(_entity,'P131'))--dargs['State']
 		setarg('TotElec', comma_value(P1867))--dargs['TotElec']
 		setarg('SuccParty', getMostSuccessfulParty(_entity) or'')
 		--setarg('Category', dargs['Category'] or '')
 		setarg('AssList',lokassmlist or '')
 
 	
 	end
 
 local function infobox(frame)
 	local abovestr =args['title'] or ''
 	local bgcolor = args['background'] or args['bgcolour'] or ''
 
 
 
 	return frame:expandTemplate{ title = 'infobox', args = {
 		[&quot;bodyclass&quot;] = &quot;vevent&quot;,
 		[&quot;bodystyle&quot;] = &quot;width:25em; text-align:left; font-size:90%;&quot;,
 		[&quot;above&quot;] = mw.ustring.format( &quot;%s [ [[d:%s|edit]] ]&quot;,abovestr ,QId),
 		[&quot;aboveclass&quot;] = &quot;summary&quot;,
 		[&quot;abovestyle&quot;] = &quot;padding-bottom:0.25em; background:&quot; .. bgcolor .. &quot;; line-height:1.2em; text-align:center; font-size:115%;&quot;,
 ------------------ Images and maps ------------------
 		[&quot;image&quot;] = args['image'] or '',
 		[&quot;imagestyle&quot;] = &quot;padding-bottom:0.5em;&quot;,
 		[&quot;caption&quot;] = args['caption'] or '',
 		[&quot;captionstyle&quot;] = &quot;padding-top:0.1em; line-height:1.2em; font-size:90%;&quot;,
 		[&quot;headerstyle&quot;] = &quot;background:#eee; font-size:105%;&quot;,
 		[&quot;labelstyle&quot;] = &quot;padding:0 0.5em 0 0; line-height:1.1em;&quot;,
 		[&quot;datastyle&quot;] = &quot;padding:0; line-height:1.2em; vertical-align:middle;&quot;,
 --		[&quot;label1&quot;] =  'Title',
 --		[&quot;data1&quot;] =  args['title'] or '',
 		
 		[&quot;label3&quot;] =  label.Existence,
 		[&quot;data3&quot;] =  args['Existence'] or '',
 		
 		[&quot;label4&quot;] =  label.Reservation,
 		[&quot;data4&quot;] =  args['Reservation'] or '',
 		
 		[&quot;label5&quot;] =  label.CurrentMP,
 		[&quot;data5&quot;] =  args['CurrMP'] or '',
 		
 		[&quot;label6&quot;] =  label.Party,
 		[&quot;data6&quot;] =  args['Party'] or '',
 		
 		[&quot;label7&quot;] =  label.ElectedYear,
 		[&quot;data7&quot;] =  args['Yr'] or '',
 		
 		[&quot;label8&quot;] =  label.State,
 		[&quot;data8&quot;] =  args['State'] or '',
 		
 		[&quot;label9&quot;] =  label.TotalElectors,
 		[&quot;data9&quot;] =  args['TotElec'] or '',
 		
 		[&quot;label10&quot;] =  label.MostSuccessfulParty,
 		[&quot;data10&quot;] =  args['SuccParty'] or '',
 		
 		[&quot;label11&quot;] =  label.Category,
 		[&quot;data11&quot;] =  args['Category'] or '',
 		
 		[&quot;label12&quot;] =  label.AssemblyConstituencies,
 		[&quot;data12&quot;] =  args['AssList'] or '',
 		
 		} }
 	
 end
 
 --fetch current elected member
 function loksabha.memberpartyref(frame)
 	args = require('Module:Arguments').getArgs(frame, {
 			wrappers = 'Template:Infobox lok sabha constituency1'  --test
 		})
 
 	if( args['2'] and args['2'] ~= '') then
 		loadloksabhadb(frame,frame.args.year .. args['1'])
 	elseif( args['1'] and args['1'] ~= '') then
 		
 		local entity=mw.wikibase.getEntityObject()
 		if entity then
 			--return entity.metatable.id
 			--return mw.dumpObject(entity)		
 		end
 		--page id
 		if(entity ) then
 			if entity.id then 			QId = entity.id; end
 		end
 
 		loadLokSabha(frame,frame.args.year  .. args['1'])
 	end
 	
 	if(args['CurrMP'] and args['CurrMP'] ~=&quot;&quot;) then
 		return (args['CurrMP'] or '') .. '(&lt;small&gt;'.. (args['Party'] or '') ..'&lt;/small&gt;)'
 	else
 		return &quot;&quot;
 	end
 	--infobox(frame)
 end
 
 --fetch current elected member
 function loksabha.currentmember(frame)
 	args = require('Module:Arguments').getArgs(frame, {
 			wrappers = 'Template:Infobox lok sabha constituency1'  --test
 		})
 
 	if( args['2'] and args['2'] ~= '') then
 		loadloksabhadb(frame,frame.args.year .. args['1'])
 	elseif( args['1'] and args['1'] ~= '') then
 		--loadloksabhadb(frame,frame.args.year  .. args['1'])
 		local entity=mw.wikibase.getEntityObject()
 		if entity then
 			--return entity.metatable.id
 			--return mw.dumpObject(entity)		
 		end
 		--page id
 		if(entity ) then
 			if entity.id then 			QId = entity.id; end
 		end
 
 		loadLokSabha(frame,frame.args.year  .. args['1'])
 	end
 	
 	return args['CurrMP'] or '' 
 	--infobox(frame)
 end
 
 function loksabha.box(frame)
 	args = require('Module:Arguments').getArgs(frame, {
 			wrappers = 'Template:Infobox lok sabha constituency1'  --test
 		})
 
 	if( args['2'] and args['2'] ~= '') then
 		loadloksabhadb(frame,frame.args.year .. args['1'])
 	elseif( args['1'] and args['1'] ~= '') then
 		--loadloksabhadb(frame,frame.args.year  .. args['1'])
 		local entity=mw.wikibase.getEntityObject()
 		if entity then
 			--return entity.metatable.id
 			--return mw.dumpObject(entity)		
 		end
 		--page id
 		if(entity ) then
 			if entity.id then 			QId = entity.id; end
 		end
 
 		loadLokSabha(frame,frame.args.year  .. args['1'])
 	end
 	
 	return infobox(frame)
 end