local p = {}

local function infobox_translate(x)
	local l10nDef = {
		["ar"] = {"تفاصيل السباق", "سلسلة", "منافسة", "مسابقات", "مراحل", "التاريخ", "التواريخ", "المسافات", "البلد", "البلدان",
			"نقطة البداية", "نقطة النهاية", "الفرق", "عدد المتسابقين في البداية", "عدد المتسابقين في النهاية", "متوسط السرعة", "الكلفة", "المنصة", "الفائز", "الثاني",
			"الثالث", "حسب النقاط", "تسلق الجبل", "سباقات السرعة", "أفضل شاب", "تصنيف القتال", "مجموعة", "الفريق", "صورة", "تعليق", "خريطة", "مميز 1", "مميز 2", "توثيق", "سباقات السرعة", "انتظام", "نقاط الفريق", "فوجا بيناريلو", "أزوري دي إيطاليا","صاعد", "هواة","الجنسية"}
	}
	local l10n = l10nDef["ar"]
	return l10n[x]
end

function p.winnertable(frame)
	local t = {class="", stage="", starttime="", endtime="", time="", date="", dates="", length="", length_unit="", 
	startplace="", endplace="", nr_teams="", nr_participants_start="", nr_participants_end="", speed="", speed_unit="", cost="", cost_unit="", 
	first="", first_team="", second="", second_team="", third="", third_team="", winner_point="", winner_point_team="", winner_mountain="", winner_mountain_team="", 
	winner_sprint="", winner_sprint_team="", winner_young="", winner_young_team="", winner_fighting="", winner_fighting_team="", winner_combination="", 
	winner_combination_team="", winner_metas_volantes="", winner_metas_volantes_team="", winner_regularity="", winner_regularity_team="", 
	winner_fuga_pinarello="", winner_fuga_pinarello_team="", winner_azzurri_ditalia="", winner_azzurri_ditalia_team="", winner_team="", 
	winner_team_points="", previous="", next=""}
	local ref = {stage="", starttime="", endtime="", time="", date="", dates="", length="", nr_participants_start="", nr_participants_end="", 
	speed="", speed_unit="", cost="", first="", second="", third="", winner_point="", winner_mountain="", winner_sprint="", winner_young="", 
	winner_fighting="", winner_metas_volantes="", winner_regularity="", winner_combination="", winner_fuga_pinarello="", winner_azzurri_ditalia="", 
	winner_team="", winner_team_points=""}
	local tt = {icon="", picture="", caption="", name="", nr="", map="" }
	local ttt = {tour={}, country={}}
	local tttt = {special_1a="", special_1b="", special_2a="", special_2b=""}
	
	local entity = ""
	local y, m, d = "", "", ""
	local y2, m2, d2 = "", "", ""
	local a, b, c, k, num, i
	local entityId = frame.args[1]
	local lang = mw.language.getContentLanguage()
	local wiki = string.match(mw.site.server, "%a+")
	local results = false
	local a1, b1, c1, a2, b2, c2
	local timeofrace

	if type( entityId ) ~= 'string' then error( 'parameter must be a string') end
	if not entityId:match( 'Q%d+' ) then error ( 'parameter must be a valid Wikidata item (ex: Q42)' ) end
	local entity = mw.wikibase.getEntity( entityId )

	local localFrame 
	if string.match(frame:getParent():getTitle(), '%P+') == mw.site.namespaces.Template.name 
	then localFrame = frame:getParent() else localFrame = frame end

	if localFrame.args[infobox_translate(29)] then tt.picture = localFrame.args[infobox_translate(29)] end 
	if localFrame.args[infobox_translate(30)] then tt.caption = localFrame.args[infobox_translate(30)] end 
	if localFrame.args[infobox_translate(31)] then tt.map = localFrame.args[infobox_translate(31)] end 

	if  entity:getLabel() ~= nil then tt.name = entity:getLabel()
	else
		if entity:getLabel( 'fr' ) ~= nil then tt.name = entity:getLabel( 'fr' ).. " (fr)"
		else tt.name = "Wikidata doesn´t know" end 
	end

	a, b = pcall(fooA, 'numeric-id', entity, 'P641', 1) 
	if a == true then -- icon for road bicycle racing, Q3609 (road bicycle racing)
		if b == 3609 then tt.icon = " [[File:Cycling (road) pictogram.svg|35px]]" end 
	end
	a, b = pcall(fooA, 'value', entity, 'P18', 1) 
	if a == true and tt.picture == "" then 
		local v
		tt.picture = b
		if pcall(foo3, entity, "P18", 1, "P2096", 1) then
			for _, v in pairs(entity.claims["P18"]) do
				for num=1,#v.qualifiers["P2096"] do
					if v.qualifiers["P2096"][num].datavalue.value.language == lang:getCode() then
					tt.caption = v.qualifiers["P2096"][num].datavalue.value.text end
				end
			end
		end
	end
	
	a, b = pcall(fooA, 'numeric-id', entity, 'P361', 1) -- Competition of the cycling race : UCI World Tour 2016, UCI Europe Tour 2016...
	if a == true then --ttt.tour = "Q" .. b end
		local i, v
		for i, v in pairs(entity.claims["P361"]) do
			ttt.tour[i] = "T" .. v.mainsnak.datavalue.value["numeric-id"]
		end
	end

-- This function give a format to dates when P585 (date) is used in a single day race
	a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', 1) 
	if a1 == true and t.time == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', i) 
		end  		
		t.time = funcDate (b1, wiki, 'long') 
		timeofrace = b1
	end


	a, b = pcall(fooA, 'numeric-id', entity, 'P17', 1) -- This function gives countries where the race take place
	if a == true then --and ttt.country == "" then ttt.country = "Q" .. b end
		local i, v
		for i, v in pairs(entity.claims["P17"]) do
   			ttt.country[i] = "C" .. v.mainsnak.datavalue.value["numeric-id"]
   		end
 	end			
	-- Function that give the starting place of a race 
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', 1) 
	if a1 == true and t.startplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', i) 
		end   
		t.startplace = "Q" .. b1 
	end	
	-- Function that give the finishing place of a race
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', 1) 
	if a1 == true and t.endplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', i) 
		end   
		t.endplace = "Q" .. b1 
	end	
	-- This function counts the number of value for P1923 (participating teams) and give the number of team that participate at the race
    if pcall(function() 
         t.nr_teams = table.getn(entity.claims["P1923"])
         end        	
      ) then else t.nr_teams = "" end   


	local note, qual, id, id_team
	-- By entering a value just below, the Wikipedia added will have Wikidata logos associated with cyclists in the infobox	
	if wiki == "www" or wiki == "mk" or wiki == "ja" or wiki == "ru" then note = 'q' 
	elseif wiki == "www" then note = 'م' 
	else note = 'f' end 
	note = 'f'
	-- By entering a value just below, the Wikipedia added will show the team of the winner
	if pcall(foo3, entity, "P1346", 1, "P642", 1) then
		local k, v, vv
		for k, v in pairs(entity.claims["P1346"]) do
			id_team = '' 
			--id_team = 't26973671'
			a, b = pcall(fooC, 'numeric-id', entity, 'P1346', k, 'P54', 1)
			if a == true then id_team = 't'..b end
		
			if pcall(function() id=v.mainsnak.datavalue.value['numeric-id'] end) then else id=nil end -- id = rider id
			if id ~= nil then
				--timeofrace = "+2016-03-00T00:00:00Z" 
				-- function timeStartEnd finds the team of the rider at the time (timeofrace) of the race
				if id_team == '' and timeofrace ~= nil and timeofrace ~= '' then 
					a, b = timeStartEnd('Q'..id, 'P54', 'numeric-id', timeofrace) 
					if a == true and b ~= nil then id_team = 't' .. b end
				end
			end
--			pcall(function() id=v.mainsnak.datavalue.value['numeric-id'] end) -- rider ID
			
			-- looks into race item if the winner has a P54 statement for beeng a member of a national team 
			pcall(function() 			
				for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P54']) do 
					id_team = '2t'.. ' ('.. national_team(wiki, 'Q'..id, timeofrace, entity, 'P1346', k).. ')' 
				end
			end)

			-- looks into race item if the winner has a P642 statement for showing the type of winner (points, mountain, ..)
			pcall(function() 			
				for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P642']) do 
					qual=vv.datavalue.value['numeric-id']

		if id~=nil and qual~=nil and v.rank~='deprecated' then 
			if qual == 20882667 and t.first=="" then t.first=note..id t.first_team=id_team ref.first=references(entity,"P1346",k) results=true end
			if qual == 20882668 and t.second=="" then t.second=note..id t.second_team=id_team ref.second=references(entity,"P1346",k) results=true end
			if qual == 20882669 and t.third=="" then t.third=note..id t.third_team=id_team ref.third=references(entity,"P1346",k) results=true end
			if qual == 20883007 and t.winner_point=="" then t.winner_point=note..id t.winner_point_team=id_team ref.winner_point=references(entity,"P1346",k) results=true end
			if qual == 20883212 and t.winner_mountain=="" then t.winner_mountain=note..id t.winner_mountain_team=id_team ref.winner_mountain=references(entity,"P1346",k) results=true end   			
  			if qual == 20883328 and t.winner_sprint=="" then t.winner_sprint=note..id t.winner_sprint_team=id_team ref.winner_sprint=references(entity,"P1346",k) results=true end
			if qual == 20883139 and t.winner_young=="" then t.winner_young=note..id t.winner_young_team=id_team ref.winner_young=references(entity,"P1346",k) results=true end  
			if qual == 20893983 and t.winner_fighting=="" then t.winner_fighting=note..id t.winner_fighting_team=id_team ref.winner_fighting=references(entity,"P1346",k) results=true end
			if qual == 27067359 and t.winner_metas_volantes=="" then t.winner_metas_volantes=note..id t.winner_metas_volantes_team=id_team ref.winner_metas_volantes=references(entity,"P1346",k) results=true end
			if qual == 27067170 and t.winner_regularity=="" then t.winner_regularity=note..id t.winner_regularity_team=id_team ref.winner_regularity=references(entity,"P1346",k) results=true end
			if qual == 20893979 and t.winner_combination=="" then t.winner_combination=note..id t.winner_combination_team=id_team ref.winner_combination=references(entity,"P1346",k) results=true end
			if qual == 27907715 and t.winner_fuga_pinarello=="" then t.winner_fuga_pinarello=note..id t.winner_fuga_pinarello_team=id_team ref.winner_fuga_pinarello=references(entity,"P1346",k) results=true end
			if qual == 27907747 and t.winner_azzurri_ditalia=="" then t.winner_azzurri_ditalia=note..id t.winner_azzurri_ditalia_team=id_team ref.winner_azzurri_ditalia=references(entity,"P1346",k) results=true end
			if qual == 20882921 and t.winner_team == "" then
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( 'Q'..id ), 'P31', 1)
				if a == true and (b == 20738667 or b == 23726798) then -- test if 'national cycling team U23' or 'national cycling team'
					t.winner_team = '2t' .." "..national_team(wiki, 'Q'..id, timeofrace, entity, 'P1346', k)
				else
					t.winner_team = note .. id ref.winner_team=references(entity,"P1346",k) results = true
				end
			end
			if qual == 27104269 and t.winner_team_points == "" then t.winner_team_points = note .. id ref.winner_team_points=references(entity,"P1346",k) results = true end
 		end
				end
			end) 
		end	-- for
	end  -- end if pcall

	-- code for references
	local list = {} -- list[1][1] = value from ref.first, list [1][2] = 'first'
	local k
	for k in pairs(ref) do 
		if ref[k]~='' then table.insert(list, {ref[k], k}) end 
	end
	local w, ww 	
	num = #list
	for w=num,1,-1 do
		for ww=1,w do
			if w ~= ww then 
				if list[w][1] == list[ww][1] then list[w][1] = frame:extensionTag{name='ref', args={name=entityId..ww}} break end	
			else list[w][1] = frame:extensionTag{name='ref', content=list[w][1], args={name=entityId..ww}} end 
		end
	end
	for i=1,num do 
		ref[ list[i][2] ] = list[i][1] --list[num+1-i][1] 
	end

	-- transform Q/q-number into flag / WPlink / WDlink
	local k
	local team = true
	local wd = " [[File:Wikidata-logo S.svg|12px|link=d:"	

	for k in pairs(ttt) do -- "^C" ttt.country, "^T" ttt.tour
		if ttt[k][1]~=nil and string.find(ttt[k][1], "^C") then for i=1,#ttt[k] do ttt[k][i] = string.gsub(ttt[k][i], "C", "Q") ttt[k][i] = flag(ttt[k][i], timeofrace).." ".. WPlink( ttt[k][i] ) end end
		if ttt[k][1]~=nil and string.find(ttt[k][1], "^T") then for i=1,#ttt[k] do ttt[k][i] = string.gsub(ttt[k][i], "T", "Q") ttt[k][i] = WPlink( ttt[k][i], 'race') end end
	end	
	for k in pairs(t) do 
		if string.find(t[k], "^Q") then --t[k], k = startplace, endplace, ... find variables with an item as value
			if pcall(foo1, t[k]) then t[k] = WPlink( t[k] )	end
		end
		if string.find(t[k], "^q") then -- find variables with an item as value (in section Résultats)
			t[k] = mw.ustring.upper( t[k] )
			--look into P27 (country of citizenship) to get the Qnumber of that country
			a, b = timeStartEnd(t[k], "P27", 'numeric-id', timeofrace)
			if a == true and pcall(foo1, t[k]) then t[k] = flag('Q'..b, timeofrace).." "..WPlink( t[k] )..ref[k]..wd..t[k].."]]"
			else
				--look into P17 (country) to get the Qnumber of that country
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P17', 1)
				if a == true and pcall(foo1, t[k]) then t[k] = flag("Q"..b, timeofrace).." "..WPlink( t[k] )..ref[k]..wd..t[k].."]]" end
			end
		end
		if string.find(t[k], "^f") then -- no WDitem, frWP
			t[k] = string.gsub(t[k], "f", "Q")
			--look into P27 (country of citizenship) to get the Qnumber of that country
			a, b = timeStartEnd(t[k], "P27", 'numeric-id', timeofrace)
			if a == true and pcall(foo1, t[k]) then t[k] = flag('Q'..b, timeofrace).." "..WPlink( t[k] )..ref[k]
			else	
				--look into P17 (country) to get the Qnumber of that country
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P17', 1)
				if a == true and pcall(foo1, t[k]) then t[k] = flag("Q"..b, timeofrace).." "..WPlink( t[k], 'team', timeofrace )..ref[k] else t[k] = WPlink( t[k], 'team', timeofrace )..ref[k] end
			end
		end	
		if string.find(t[k], "^c") then -- find "class"-items, first asci = "c"
			t[k] = string.gsub(t[k], "c", "Q")
			if pcall(foo1, t[k]) then t[k] = WPlink( t[k], "Q22348500" ) end
		end
		if string.find(t[k], "^t") then 
			t[k] = string.gsub(t[k], "t", "Q")
			--timeofrace = "+2008-04-09T00:00:00Z"
			if pcall(foo1, t[k]) then t[k] = " (" .. WPlink( t[k], 'team', timeofrace ) .. ")" end
		end
		if string.find(t[k], "^2t") then t[k] = string.gsub(t[k], "2t", "") end		
	end

    --local nl ="
"
    -- local tooltip = infobox_bottom(2) .. nl .. mw.text.encode( property(1) .. ' (P393)' ) .. nl .. mw.text.encode( property(2) ..' (P17)')
    
    if t.length ~= "" then 
    	t.length, _ = string.gsub(t.length, "[+]", "") -- delets "+" sign from t.length 
    	t.length = lang:formatNum(tonumber(t.length)) -- formats t.length in the way it is done in the local Wiki
    	if wiki == 'fo' then t.length = string.gsub(t.length, "%.", ",") end
    end    
    if t.speed ~= "" then 
    	t.speed, _ = string.gsub(t.speed, "[+]", "")
    	t.speed = lang:formatNum(tonumber(t.speed))
    	if wiki == 'fo' then t.speed = string.gsub(t.speed, "%.", ",") end
    end
    if t.cost ~= "" then 
    	t.cost, _ = string.gsub(t.cost, "[+]", "")
    	t.cost = lang:formatNum(tonumber(t.cost))
    	if wiki == 'fo' then t.cost = string.gsub(t.cost, "%.", ",") end
    end
    
   	local span1, span2 = "<span style='color:#3366CC'>&#x25C0; </span>", "<span style='color:#3366CC'> &#x25B6;</span>"
    local k = t.previous
	local i, _ = string.find(k, "|")
	local j, _ = string.find(k, "]")
	if i ~= nil and j ~= nil then 
		t.previous = string.sub(k, 1, i) .. span1 .. (string.match(string.sub(k, i+1, j-1), "%d%d%d%d") or '') .. string.sub(k, j) 
	else 
		if string.find(k, "%d%d%d%d") == nil then t.previous = '' else t.previous = string.sub(k, string.find(k, "%d%d%d%d")) end
		if t.previous ~= "" then t.previous = span1 .. t.previous end 
	end

	k = t.next
	i, _ = string.find(k, "|")
	j, _ = string.find(k, "]")
	if i ~= nil and j ~= nil then 
		t.next = string.sub(k, 1, i) .. (string.match(string.sub(k, i+1, j-1), "%d%d%d%d") or '') .. span2 .. string.sub(k,j) 
	else 
		if string.find(k, "%d%d%d%d") == nil then t.next = "" else t.next = string.sub(k, string.find(k, "%d%d%d%d")) end
		if t.next ~= "" then t.next = t.next .. span2 end 
	end

	tt.caption = string.gsub(tt.caption, "{{(%w+)}}", function (n) return frame:expandTemplate{ title = n }  end)
	-- for overwriting Wikidata content with data in Wikipedia articles. numbers are from function infobox_translate
	local z = {stage=5, date=6, dates=7, length=8, startplace=11, endplace=12, nr_teams=13, nr_participants_start=14, nr_participants_end=15, 
	speed=16, cost=17, first=19, second=20, third=21, winner_point=22, winner_mountain=23, winner_sprint=24, winner_young=25, winner_fighting=26, 
	winner_combination=27, winner_team=28, winner_team_points=37, winner_metas_volantes=35, winner_regularity=36, winner_fuga_pinarello=38,
	winner_azzurri_ditalia=39}

 	tab = "{| cellpadding='4' cellspacing='0' style='float:left; width:300px; border:1px solid rgb(200,200,200);"
    tab = tab .. "margin:0 0 0.5em 0.5em; background-color:rgb(255, 255, 255); color:black; padding:5px; clear:left; "
    tab = tab .. "text-align:right; font-size:85%; line-height:1.6em;"
	if results then tab = tab.."|- \n| colspan='2' style='border-bottom:5px solid white; background-color:#FFDF80; text-align:center' | '''"..infobox_translate(18).."'''\n" end
	if t.first ~= "" then tab = tab.."|-\n|'''"..infobox_translate(19).."'''||" .. t.first .. "\n" end
	if t.second ~= "" then tab = tab.."|-\n|'''"..infobox_translate(20).."'''||" .. t.second .. "\n" end
	if t.third ~= "" then tab = tab.."|-\n|'''"..infobox_translate(21).."'''||" .. t.third .. "\n" end
	if t.winner_point ~= "" then tab = tab.."|-\n|'''"..infobox_translate(22).."'''||" .. t.winner_point .. "\n" end
	if t.winner_mountain ~= "" then tab = tab.."|-\n|'''"..infobox_translate(23).."'''||" .. t.winner_mountain .. "\n" end
	if t.winner_sprint ~= "" then tab = tab.."|-\n|'''"..infobox_translate(24).."'''||" .. t.winner_sprint .. "\n" end
	if t.winner_young ~= "" then tab = tab.."|-\n|'''"..infobox_translate(25).."'''||" .. t.winner_young .. "\n" end
	if t.winner_fighting ~= "" then tab = tab.."|-\n|'''"..infobox_translate(26).."'''||" .. t.winner_fighting .. "\n" end
	if t.winner_metas_volantes ~= "" then tab = tab.."|-\n|'''"..infobox_translate(35).."'''||" .. t.winner_metas_volantes .. "\n" end
	if t.winner_regularity ~= "" then tab = tab.."|-\n|'''"..infobox_translate(36).."'''||" .. t.winner_regularity .. "\n" end
	if t.winner_fuga_pinarello ~= "" then tab = tab.."|-\n|'''"..infobox_translate(38).."'''||" .. t.winner_fuga_pinarello .. "\n" end
	if t.winner_azzurri_ditalia ~= "" then tab = tab.."|-\n|'''"..infobox_translate(39).."'''||" .. t.winner_azzurri_ditalia .. "\n" end
	if t.winner_combination ~= "" then tab = tab.."|-\n|'''"..infobox_translate(27).."'''||" .. t.winner_combination .. "\n" end
	if t.winner_team ~= "" then tab = tab.."|-\n|'''"..infobox_translate(28).."'''||" .. t.winner_team .. "\n" end
	if t.winner_team_points ~= "" then tab = tab.."|-\n|'''"..infobox_translate(37).."'''||" .. t.winner_team_points .. "\n" end

	--tab = tab.."<tr><td style='text-align:right'>"..t.previous.."</td><td style='text-align:left'>" .. t.next .. "\n"
	--tab = tab.."|-\n|"..t.previous.."</td><td style='text-align:right'>" .. t.next .. "\n"
	local s = "d:Wikidata:WikiProject Cycling/Documentation/infobox"
	tab = tab .. "|- \n| colspan='2' style='text-align:left; border-top:3px solid #FFDF80; font-size:75%' | " .. "[[" .. s .. "|" .. infobox_translate(34) .. "]] [[File:Wikidata-logo S.svg|12px|link=d:".. frame.args[1]  .. "]]" --infobox_bottom(1) 
	--tab = tab .. "<span style='float:right' title='".. tooltip .. "'>[[File:High-contrast-help-browser.svg|10px|right|link=]]"	
	--tab = tab .. "</span>\n"
	tab= tab.."\n|}"
	return tab
end

return p