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, "^(-?%d+)(%d%d%d)", '%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( "update at :[[:wikidata:%s|%s]]", _entity.id, _entity.id..':'.. propertyName )
		end
	
		if propValue['type'] == 'wikibase-entityid' then
			local linkTarget = mw.wikibase.sitelink( "Q" .. propValue.value['numeric-id'] )
			local linkTitle = mw.wikibase.label( "Q" ..propValue.value['numeric-id'] )
			return linkTarget and linkTitle and mw.ustring.format( "[[%s|%s]]", 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 = "+(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z"
	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=="time"  and v2.snaktype=="novalue" then

						table.insert(out, v2.snaktype)
					end
				end
			end
		end
		return out
	else
		return ""
	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="";

	if a~=nil then
		for k,v in ipairs(a) do
			if str ~="" then	str= str.."<br>" end
			if  tonumber(v) and tonumber(b[k]) and tonumber(v)<tonumber(b[k]) then
				str=tostring(str) .. tostring(v) .." - ".. tostring(b[k])
			elseif  tonumber(b[k]) ==nil then
				if b[k]=="novalue" or b[k]==nil then b[k]= label.Present; end --mw.wikibase.label("Q193168") or "[[d:Q193168|]]" end --present
				str=tostring(str) .. tostring(v) .." - ".. tostring(b[k])	
			end
		end
	else
		str="Start Time Property value <br />missing at [[d:".. _entity.id ..":P31:P580]]"
	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 =  "Q" .. 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( "[[%s|%s]]", mw.wikibase.sitelink(scst), mw.wikibase.label(classification))	
		else
			return mw.ustring.format( "[[%s]]", 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="Qualifier Political party (102) is missing under P585 in [[d:".. QId .."]]";
	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( "[[%s|%s]]", mw.wikibase.sitelink(partyid), _shortname)	
		else
			str= mw.ustring.format( "[[%s]]", mw.wikibase.sitelink(partyid))
		end	
	else
		str= mw.wikibase.label(partyid) or "Political party (P102) is missing at [[d:".. QId .."]]";
	end
	
	return str
end
function getCurrentMP(_id)
	local propertyID ="P991" --successful candidate
	local str="Current MP (Successful candidate - P991) name is missing at [[d:".. QId .."]]";
	if _id==nil then return str;
		
	elseif	ifexist(mw.wikibase.sitelink(_id)) then
		str=mw.ustring.format( "[[%s|%s]]", mw.wikibase.sitelink(_id), mw.wikibase.label(_id))	
		
	elseif mw.wikibase.label(_id) then
		str= mw.ustring.format( "[[%s]]", mw.wikibase.label(_id))
	else
		str=_id
	end

	return str;
end

function getMostSuccessfulParty(_entity)

	party_list={}
	local propertyID='P585' --point in time	
	if _entity.claims[propertyID]  then
		local pattern="+(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z"

		for k, v in pairs(_entity.claims[propertyID]) do
			P585Qual = v['qualifiers'];
			
			if P585Qual['P102']~=nil then S102=P585Qual['P102'][1].datavalue.value['numeric-id']; end --classification
			local string s=mw.ustring.format("%s",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 > max_val then
			max_val, key = v, k
		end
	end

	if key~=nil then
		_shortname=getShortName('Q'..key);
  		if _shortname~=nil then
			party=mw.ustring.format("[[%s|%s]]", mw.wikibase.sitelink('Q'..key), _shortname)
		elseif mw.wikibase.sitelink('Q'..key) ~=nil then
			party=mw.ustring.format("[[%s]]", mw.wikibase.sitelink('Q'..key) )
		else
			party=mw.ustring.format("[[:d:%s]]", mw.wikibase.label('Q'..key) or 'Q'..key)
		end
		
		return mw.ustring.format("%s \(%s %s\)",party, max_val,label.Times)
	else
		return ""
	end
end

function getImage(_entity)
	local property=getPropertyByEntity(_entity, 'P242' )
	if  property~=nil then
		return mw.ustring.format( "[[File:%s|220px]]", 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 ="Image Legend qualifier <br />missing at [[d:".. _entity.id ..":P242:P2096]]";
	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( "%s", property)	
		else
			return ''			
		end
	end
	
	local function assemblylist(_entity)
		--has part P527
		--local Qid="Q7785493"
		local propertyID ="P527"--has part
		--local entity = mw.wikibase.getEntityObject(Qid)
		local str=""
		if _entity.claims[propertyID] ~= nil then
			for k, v in pairs(_entity.claims[propertyID]) do
				if str ~="" then	str= str.."<br>" end
				local id='Q' ..v.mainsnak.datavalue.value['numeric-id']
				local series=getProperty(id,'P1545')
				if series~=nil then series=series ..". " end
				if  mw.wikibase.sitelink(id) ~=nil and mw.wikibase.label(id)~=nil then
					str =str .. (series or '') .. mw.ustring.format( "[[%s|%s]]", mw.wikibase.sitelink(id), mw.wikibase.label(id))
				elseif mw.wikibase.label(id)~=nil then
					str =str .. (series or '') .. mw.ustring.format( "[[%s]]",mw.wikibase.label(id))
					
				else
					str =str .. (series or '') ..mw.ustring.format( "[[:d:%s]]",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
		
		if _entity.claims[propertyID]  then
			P585Qual = _entity.claims[propertyID][1]['qualifiers']
			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 =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', 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 = {
		["bodyclass"] = "vevent",
		["bodystyle"] = "width:25em; text-align:left; font-size:90%;",
		["above"] = mw.ustring.format( "%s [ [[d:%s|edit]] ]",abovestr ,QId),
		["aboveclass"] = "summary",
		["abovestyle"] = "padding-bottom:0.25em; background:" .. bgcolor .. "; line-height:1.2em; text-align:center; font-size:115%;",
------------------ Images and maps ------------------
		["image"] = args['image'] or '',
		["imagestyle"] = "padding-bottom:0.5em;",
		["caption"] = args['caption'] or '',
		["captionstyle"] = "padding-top:0.1em; line-height:1.2em; font-size:90%;",
		["headerstyle"] = "background:#eee; font-size:105%;",
		["labelstyle"] = "padding:0 0.5em 0 0; line-height:1.1em;",
		["datastyle"] = "padding:0; line-height:1.2em; vertical-align:middle;",
--		["label1"] =  'Title',
--		["data1"] =  args['title'] or '',
		
		["label3"] =  label.Existence,
		["data3"] =  args['Existence'] or '',
		
		["label4"] =  label.Reservation,
		["data4"] =  args['Reservation'] or '',
		
		["label5"] =  label.CurrentMP,
		["data5"] =  args['CurrMP'] or '',
		
		["label6"] =  label.Party,
		["data6"] =  args['Party'] or '',
		
		["label7"] =  label.ElectedYear,
		["data7"] =  args['Yr'] or '',
		
		["label8"] =  label.State,
		["data8"] =  args['State'] or '',
		
		["label9"] =  label.TotalElectors,
		["data9"] =  args['TotElec'] or '',
		
		["label10"] =  label.MostSuccessfulParty,
		["data10"] =  args['SuccParty'] or '',
		
		["label11"] =  label.Category,
		["data11"] =  args['Category'] or '',
		
		["label12"] =  label.AssemblyConstituencies,
		["data12"] =  args['AssList'] or '',
		
		} }
	
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

return loksabha