Dokumentation [visa] [redigera] [historik] [rensa sidcachen]


Detta är en modul för att visa information om idrottare. Den används för närvarande främst för lagidrotter (inte minst volleyboll), den fungerar ännu inte lika bra för idrotter med grenar (som friidrott, simning och brottning). Moduler visar information som spelposition och under vilken tid de spelat för olika klubbar och landslag samt resultat i form av framförallt placeringar vid olika turneringar. Modulen hämtar datauppgifter från Wikidata och lägger in det i Mall:Faktamall. Modulen används av Mall:Sportperson WD. För tips om användning se där. Nedan är dokumentation om själva modulen.

Funktioner

redigera

Modulen anropas genom att lägga in {{#Invoke:Sportperson WD | person}} i artikeln (eller som nämnt ovan genom att använda mallen Sportperson WD). Den tar följande argument:

  • id: "Q-ID" för en person (t.ex. Q22338719 för Isabelle Haak (Q22338719), Isabelle Haak). I normalfallet behöver detta inte anges då funktionen använder det wikidataobjekt som är länkar till artikeln.
  • lastchecked: Datum på formatet ÅÅÅÅMMDD. Denna används för att skriva när uppgifterna i Wikidata senast kontrollerades av en användare på den lokala wikipedian.

Beskrivning

redigera

Modulen består av följande delar:

  • Personlig data (bild (P18), födelsedatum (P569), födelseplats (P19) och spelarposition (P413)). Uppgifterna hämtas från motsvarande uppgifter i Wikidata.
  • Uppgifter om klubbar som personen spelat för. Detta omfattar dels:
    • Klubbarna personen har spelat för med start och slutår. Uppgifterna hämtas från motsvarande uppgifter i Wikidata (medlem i idrottslag (P54)), med årtalen som bestämning.
    • Resultat för klubbarna som personen har spelat för (placering, typ av tävling och tid för tävlingsupplagan). Uppgifter från dess hämtas från uppgiften deltog i (P1344) från Wikidata. Koden läser av klubbens placering i tävlingen antingen direkt från posten eller genom att hitta spelaren lag från tävlingens deltagande lag (P1923). Den läser av tiden för tävlingen genom att läsa av uppgifter från tävlingens wikidata-objekt, antingen direkt genom (startdatum (P580) eller slutdatum (P582)) eller indirekt genom att först läsa tidsperiod (P2348) och sedan läsa motsvarande uppgifter därifrån. Om relevanta uppgifter inte finns anpassas visningen så att infoboxen blir så lättläst som möjligt.
  • Uppgifter om landslag som personen spelat för fylls i på samma sätt. Dessa fungerar på samma sätt som för klubbarna, med enda skillnaden är att de är landslag. Ett lag räknas som landslag om deras instans av (P31) är landslag (Q1194951). Klubblag har istället instans av (P31) som är antingen idrottsförening (Q847017), idrottslag (Q12973014) eller volleybollklubb (Q108395614) eller är instans av något som i sin tur är instans av någon av de tre listade typerna.
  • Uppgifter om lag (klubblag eller landslag) som personen tränat. Detta fungerar på samma sätt som klubblag eller landslag som personen spelat för, men tas istället från tränare för idrottslag (P6087).
  • Individuella utmärkelser (utmärkelse (P166)). Uppgifterna hämtas från motsvarande uppgifter i Wikidata.

För alla delar gäller att de bara visas i infoboxen om det finns några inlagda uppgifter (t.ex. visas inte individuella utmärkelser om det inte finns några inlagda).

Felsökning

redigera

Modulen försöker visa ett meddelande direkt i sidan om information saknas på wikidata som gör att den inte kan visa informationen på det sätt som det är tänkt. Vanligen kan fel åtgärdas genom att lägga in rätt uppgifter i wikidata. Om du får ett meddelande som börjar Luafel i Modul:Sportperson_WD skriv gärna ett meddelande på modulens diskussionssida.

Exempel på fel och åtgärder:

  • Tävling sorteras fel (i början istället för längre ner i tabellen) - Tävlingar sorteras i första hand på när de avslutats och i andra hand efter när de börjat. Om det inte finns någon datum hamnar de först. Gå till den aktuella tävlingen i wikidata och lägg in startdatum (P580) eller slutdatum (P582) (eller tidsperiod (P2348), men då måste den i sin tur ha startdatum (P580) och/eller slutdatum (P582)).
  • "Tävling ej satt" - Detta felet beror på att det aktuella tävlingstillfället saknar en sportsäsong av serie eller tävling (P3450). Ett mycket vanligt exempel på detta är att någon är satt som att den har deltagit i ett olympiskt spel (hela arrangemanget, t.ex. Olympiska sommarspelen 1972 (Q8438)) istället för den enskilda tävlingen vid det olympiska spelet, t.ex. Herrarnas turnering i volleyboll vid olympiska sommarspelen 1972 (Q1005689).
  • Tävlingsresultat visas inte. För att ett tävlingsresultat där personen deltagit som del av ett lag (angett med bestämningen medlem i idrottslag (P54)) ska visas måste det också vara inlagt att personen varit medlem i laget. Du behöver alltså lägga in medlem i idrottslag (P54) som uttalande direkt för personen.
  • Resultat med en klubb eller ett landslag hamnar inte under de rubrikerna. Detta felet beror på att resultatet inte är inlagt med bestämningen medlem i idrottslag (P54). Det är alltså inte i Wikidata angivet i vilket lag personen spelade. I detta fallet antar modulen att detta beror på att det är för att tävlingen var en individuell tävling (a la. 100 meter i friidrott eller singel i bordtennis) och då hamnar resultat överst.

Kategorier för artiklar där fel förekommer

redigera

Mer allvarliga (information visas inte korrekt)

Mindre allvarliga (information som helst ska finnas saknas)

Övriga fel

p = {}

local rh = require( 'Modul:Referenshantering' )
local sd = require( 'Modul:Sportdata')

txtAwardMissingYear="Artiklar med utmärkelse utan tidsangivelse"
txtMissingSport="Artiklar med idrottare utan angiven sport"
txtMissingDatesplayed="Artiklar med idrottare med klubb- eller landslagsaktivitet som saknar både start- och slutdatum"
txtTeamPlayedMissingSport="Artiklar där minst ett klubb-/landslag som idrottaren spelat med inte visas p.g.a. att det inte har sport angiven"
txtTeamCoachedMissingSport="Artiklar där minst ett klubb-/landslag som idrottaren tränat inte visas p.g.a. att det inte har sport angiven"
txtCompetitionMissingSport="Artiklar där minst ett resultat saknas p.g.a. att tävlingen inte har sport angiven"
txtCompetitionMissingCompetitionRank="Artiklar där minst en tävling saknar rang"
p.iRefcounter=0

p.tblSportWithGoals={Q2736=true,Q8418=true,Q183018=true,Q41466=true,Q1455=true,Q185851=true,Q231200=true,Q134211=true,Q850256=true,Q7707=true}
-- Association football, handboll, bandy, ice hockey, field hockey, lacrosse, netball, polo, shinty, water polo

p.infobox = function(frame)
	p=p.data(frame)
	if (p.objectMainId) then
	    myArgs={titel=p.label,grundstil="width:" .. txtWidth_px}
	    myArgs[txtHeaderStyle] = txtStyleMain
		if p.image then
			showImage(p.image)
			end
		p.iViewAlternativeTemporalData=1
		p.iCounter=0
	    p.showpartininfobox(txtNickNameLabel,'nickname')
	    p.showpartininfobox(txtBirthDateLabel,'birthdate',false,p.showage)
	    p.loopitems(txtBirthPlaceLabel,'birthlocation',showPlace)
	    p.showpartininfobox(txtDeathDateLabel,'deathdate',false,p.showlifespan)
	    if (p.deathdate) then
	    	p.loopitems(txtDeathPlaceLabel,'deathlocation',showPlace)
	    	end
	    p.showpartininfobox(txtHeightLabel,'height_cm')
	    p.loopitems(txtPlayerPositionLabel,'positions',nil,{'data'},', ',' och ')
	    p.loopitems(txtSportLabel,'arraySports_Occupation',nil,{'data'},', ',' och ')
	
	    if (#p.arraySports_Occupation==0) then p.bMissingSport=true end
	    p.iTotalTeamsPlayed=#p.teams_played
	    p.iTotalTeamsCoached=#p.teams_coached
	    p.iResults=#p.results
	    
	    p.iTotalTeamsPlayed_handled=0
	    p.iTotalTeamsCoached_handled=0
	    p.iResults_handled=0
	    for i=1,#p.arraySports_Occupation do
	
			-- Process who they played for and the results (but do not present it yet)
			--Played in club
			local clubteams_played=p.filter_advanced(p,'teams_played',{'sports','isclub'},{p.arraySports_Occupation[i].id,true})
			local playedinclubteams_result=p.filter_advanced(p,'results',{'iSport','bIsClub','bPlayed'},{p.arraySports_Occupation[i].id,true,true})
	
			p.iTotalTeamsPlayed_handled=p.iTotalTeamsPlayed_handled+#clubteams_played
		    p.iResults_handled=p.iResults_handled+#playedinclubteams_result
				
			--Played in national team
			local nationalteams_played=p.filter_advanced(p,'teams_played',{'sports','isnationalteam'},{p.arraySports_Occupation[i].id,true})
			local playedinnationalteams_result=p.filter_advanced(p,'results',{'iSport','bIsNationalTeam','bPlayed'},{p.arraySports_Occupation[i].id,true,true})

			p.iTotalTeamsPlayed_handled=p.iTotalTeamsPlayed_handled+#nationalteams_played
		    p.iResults_handled=p.iResults_handled+#playedinnationalteams_result
	
			--Coach of club
			local clubteams_coached=p.filter_advanced(p,'teams_coached',{'sports','isclub'},{p.arraySports_Occupation[i].id,true})
			local coachedclubteams_result=p.filter_advanced(p,'results',{'iSport','bIsClub','bCoached'},{p.arraySports_Occupation[i].id,true,true})

			p.iTotalTeamsCoached_handled=p.iTotalTeamsCoached_handled+#clubteams_coached
		    p.iResults_handled=p.iResults_handled+#coachedclubteams_result
	
			--Coach of national team
			local nationalteams_coached=p.filter_advanced(p,'teams_coached',{'sports','isnationalteam'},{p.arraySports_Occupation[i].id,true})
			local coachednationalclubteams_result=p.filter_advanced(p,'results',{'iSport','bIsNationalTeam','bCoached'},{p.arraySports_Occupation[i].id,true,true})

			p.iTotalTeamsCoached_handled=p.iTotalTeamsCoached_handled+#nationalteams_coached
		    p.iResults_handled=p.iResults_handled+#coachednationalclubteams_result

			-- Individual results
			local individualresults=p.filter_advanced(p,'results',{'iSport','bIsNationalTeam','bIsClub'},{p.arraySports_Occupation[i].id,false,false})

		    p.iResults_handled=p.iResults_handled+#individualresults

			bHasIndividualResults=(#clubteams_played>0)	or (#clubteams_coached>0) or (#nationalteams_played>0)	or (#nationalteams_coached>0) or (#individualresults>0)	
	    	if ((#p.arraySports_Occupation>1) and bHasIndividualResults) then -- Only show sports header if more than one sport
			    p.addHeader(firstToUpper(p.arraySports_Occupation[i].data_plain),'background:#555555;color:#ffffff')
			    end
	
			if(p.tblSportWithGoals[p.arraySports_Occupation[i].id]) then
					tblThirdColumn={{width=40,title=p.frame:expandTemplate{title=txtTooltiptemplate,args={txtPlayedGamesScoreGoalsShort,txtPlayedGamesScoreGoals}},func=p.thirdcolumn}}		
				else
					tblThirdColumn=nil
				end
	
			-- Show who they have played with and their results
			p.showtemporalpartininfobox(txtClubTeamPlayHeader,nil,txtClubTeamHeader,clubteams_played,nil, false,tblThirdColumn)
			p.resulttable(playedinclubteams_result,'background:'..txtResultColour..';')
	
			p.showtemporalpartininfobox(txtNationalTeamPlayHeader,nil,txtNationalTeamHeader,nationalteams_played,showcountry,false,tblThirdColumn)
			p.resulttable(playedinnationalteams_result,'background:'..txtResultColour..';')
	
			p.showtemporalpartininfobox(txtCoachHeader,nil,txtClubTeamHeader,clubteams_coached)
			p.resulttable(coachedclubteams_result,'background:'..txtResultColour..';')
	
			p.showtemporalpartininfobox(txtNationalTeamCoachHeader,nil,txtNationalTeamHeader,nationalteams_coached,showcountry)
			p.resulttable(coachednationalclubteams_result,'background:'..txtResultColour..';')
	
			p.resulttable(individualresults,'background:'..txtResultColour..';')
		    end
	
		if p.awards then
			p.addHeader(txtIndividualAwards)
			p.awardtable()
			end
	
		local txtLastChecked=frame.args['lastchecked']
		if ((not isempty(txtLastChecked)) and (#txtLastChecked==8)) then
			local yearLastChecked=tonumber(string.sub(txtLastChecked,1,4))
			local monthLastChecked=tonumber(string.sub(txtLastChecked,5,6))
			local dayLastChecked=tonumber(string.sub(txtLastChecked,7,8))
			local argsLastChecked={dayLastChecked,monthLastChecked,yearLastChecked}
			local argsUpdateAfter={yearLastChecked+3,monthLastChecked,dayLastChecked,"","[[" .. txtCategory .. ":" .. txtNotUpdatedCategory .. "]]"}
			--Empty row added for esthetic reasons, to separate the date from the rest of the infobox
			p.iCounter=p.iCounter+1
			myArgs[txtContent .. p.iCounter]="   "
	
			--Write out the when data last checked, include a note about what is meant by the date
			p.iCounter=p.iCounter+1
			myArgs[txtLabel .. p.iCounter]=txtLastCheckedLabel .. frame:extensionTag("ref", txtLastCheckedLabel_Clarification)
			myArgs[txtContent .. p.iCounter]=frame:expandTemplate{title=txtDMYtemplate,args=argsLastChecked} .. frame:expandTemplate{title=txtShowAftertemplate,args=argsUpdateAfter}
			end	
		
	    -- Under --
		myArgs['under']='[https://www.wikidata.org/wiki/' .. p.objectMainId .. ' '.. txtEditComment .. ']'
	--	if (tblThirdColumn) then
	--		myArgs['under']=myArgs['under'].. tprint(tblThirdColumn) .. #tblThirdColumn 
	--		end
		p.dochecks()
		return frame:expandTemplate{ title = txtTemplate .. ':' .. txtInfoboxTemplate , args =myArgs}
		end
end

p.dochecks=function()
	if (p.iCounter<2) then
		myArgs['under']=myArgs['under']..'[['..txtCategory .. ':' .. txtFewItems .. ']]'
	end
	if (p.bMissingSport) then
		myArgs['under']=myArgs['under']..'[['..txtCategory .. ':' .. txtMissingSport .. ']]'
	end
	bHasTeamsWithoutDates=false
	for i=1,#p.teams_played do
		local team_played=p.teams_played[i]
		if (not team_played.from) and (not team_played.to) then bHasTeamsWithoutDates=true break end
		end
	if (bHasTeamsWithoutDates) then
		myArgs['under']=myArgs['under']..'[['..txtCategory .. ':' .. txtMissingDatesplayed .. ']]'
	end
	if (p.iTotalTeamsPlayed_handled<p.iTotalTeamsPlayed) then
		myArgs['under']=myArgs['under']..'[['..txtCategory .. ':' .. txtTeamPlayedMissingSport .. ']]'
		end
	if (p.iTotalTeamsCoached_handled<p.iTotalTeamsCoached) then
		myArgs['under']=myArgs['under']..'[['..txtCategory .. ':' .. txtTeamCoachedMissingSport .. ']]'
		end
	if (p.iResults_handled<p.iResults) then
		myArgs['under']=myArgs['under']..'[['..txtCategory .. ':' .. txtCompetitionMissingSport .. ']]'
		end
	local unrankedcompetition=p.filter_advanced(p,'results',{'iCompetitionRank'},{9999999})
	if (#unrankedcompetition>0) then
		myArgs['under']=myArgs['under']..'[['..txtCategory .. ':' .. txtCompetitionMissingCompetitionRank .. ']]'
		end

--		myArgs['under']=myArgs['under']..'Played' .. ': ' .. p.iTotalTeamsPlayed_handled .. '(' .. p.iTotalTeamsPlayed .. ')'
--		myArgs['under']=myArgs['under']..'Coached' .. ': ' .. p.iTotalTeamsCoached_handled .. '(' .. p.iTotalTeamsCoached .. ')'
--		myArgs['under']=myArgs['under']..'Results' .. ': ' .. p.iResults_handled .. '(' .. p.iResults .. ')'
end

p.data = function(frame)
	p.frame=frame
	if (frame.args['qid']) then
		p.objectMainId=frame.args['qid'] else
		p.objectMainId=mw.wikibase.getEntityIdForCurrentPage()
	end
	-- get main id (if set in call use that, otherwise use connected object)
	if (p.objectMainId) then
		tmpBasicData=getGeneralInformation(p.objectMainId,true)
		p=merge(p,tmpBasicData)
		p.objectIds={}
		end
	return p
end

function getGeneralInformation(qid,ismain)
	local ret={}
	ret.label=getLabelByEntity(qid)
	ret.image=getImage(qid,'P18')
	ret.txtNickName=useStatement(qid, 'P1449' )
	ret.birthdate=readFirstStatementFlexible(qid, 'P569','time')
	if ret.birthdate then
		ret.birthlocation=getLocation (qid,'P19',false,ret.birthdate.date)
		else
		ret.birthlocation=getLocation (qid,'P19',false)
		end
	ret.alive=true
	ret.deathdate=readFirstStatementFlexible(qid, 'P570','time' )
	if (ret.deathdate) then
		ret.alive=false
		ret.deathlocation=getLocation (qid,'P20',false,ret.deathdate.date)
	end
	ret.positions=useStatement(qid, 'P413' )
	ret.height_cm=getHeight(qid)
	ret.arraySports=useStatement(qid, 'P641' )
	ret.arraySports_Occupation=getSportOccupation(qid)
	ret.teams_played=getTeams(qid,'P54')
	ret.teams_coached=getTeams(qid,'P6087')
	ret.results=getResults(qid)
	ret.awards=useStatement(qid, 'P166','function',{'P585','P1027'},p.fillAward)
	return ret
end

p.fillAward=function(tblAward,value)
	tbl={}
	tbl.year=readDate(value,'P585')
	if (not tbl.year) and tblAward.P1027 then
		values=mw.wikibase.getBestStatements(tblAward.P1027,'P585')
		if (values[1]) then
			tmp={}
			tmp.raw=read(values[1],'time')
			tmp.year=string.sub(tmp.raw,2,5)
			tbl.year=tmp
			end
		values=mw.wikibase.getBestStatements(tblAward.P1027,'P580')
		if (values[1]) then
			tmp={}
			tmp.raw=read(values[1],'time')
			tmp.year=string.sub(tmp.raw,2,5)
			tbl.from=tmp
			end
		values=mw.wikibase.getBestStatements(tblAward.P1027,'P582')
		if (values[1]) then
			tmp={}
			tmp.raw=read(values[1],'time')
			tmp.year=string.sub(tmp.raw,2,5)
			tbl.to=tmp
			end
		end
	if not tbl.to then
		tbl.from=tbl.year -- for sorting purposes
		tbl.to=tbl.year -- for sorting purposes
		end
	if tblAward.P1027 then
		tbl.competitiontype=useStatement(tblAward.P1027,'P3450')
		end
	return tbl
end

function iGender(idTeam)
	-- Read property 'competition class'
	claimsCompetitionClass = mw.wikibase.getBestStatements(idTeam, 'P2094' )
	-- If had value ..
	if next(claimsCompetitionClass) then
		-- .. read the value
    	local idCompetitionClass = read(claimsCompetitionClass[1],'id')
    	-- for the competition class check what it is underclass to
		claimsGender = mw.wikibase.getBestStatements(idCompetitionClass, 'P279' ) -- Subclass
		-- loop through the claims to check if it is either women's or men's sport.
	    for key, value in pairs( claimsGender ) do
    		idGender = read(value,'id')
    		-- Is it men's sport?
			if (idGender=='Q35555522') then
				return 1
			end
    		-- Is it women's sport?
			if (idGender=='Q920057') then
				return 2
				end
	    end
	end
	return 0		-- If nothing found return 0
end

p.awardrow=function(awarditem)
	local txtTitle
	if awarditem.competitiontype then
			txtTitle='[[' .. mw.wikibase.getSitelink(awarditem.competitiontype.id) .. '|' .. getLabelFromEntityId(awarditem.id) .. ' (' .. getLabelFromEntityId(awarditem.competitiontype.id) .. ')]]'
		else
			txtTitle= txtWikilink(awarditem.id)
		end
	local txtYear
	if (awarditem.year) then
		txtYear=awarditem.year.year
		else
			if (awarditem.from and awarditem.to) then
				txtYear=txtYears(awarditem.from.year,awarditem.to.year,'/')
				else
				txtYear='[[' .. txtCategory .. ':' .. txtAwardMissingYear .. ']]'
				end
		end
	return '<tr><td style="text-align:left">' .. txtYear .. '</td><td style="text-align:left">'..txtTitle..txtUnpackReference_model(p.frame,awarditem.ref,awarditem.qid,awarditem.pid) ..'</td>'
end

p.awardtable=function()
p.iCounter=p.iCounter+1
local txt='<table style="class: biography vcard" width="100%"><tr><th width="60px">' .. txtSeasonHeader .. '</th><th>' ..txtAward .. '</th>'
if (#p.awards)>1 then
    table.sort(p.awards, standarddatesearch)		
	for i=1,#p.awards do
		local award=p.awards[i]
		txt=txt..p.awardrow(award)
	end
	else
		txt=txt..p.awardrow(p.awards)
	end
myArgs[txtContent .. p.iCounter]=txt .. '</table>'
mylog=''

end

function tblNationalTeamInfo(qid)
	tbl={}
	claimsInstanceOf = mw.wikibase.getBestStatements(qid, 'P31' )
	tbl.bIsReserve=false
    for key, value in pairs( claimsInstanceOf ) do
		if (read(value,'id') == 'Q45053817') then tbl.bIsReserve=true end
	end

	claimsCountry = mw.wikibase.getBestStatements(qid, 'P1532' )
	if (not next(claimsCountry)) then
		claimsCountry = mw.wikibase.getBestStatements(qid, 'P17' )
		end	
	tbl.id=read(claimsCountry[1],'id')
	tbl.txtName = getLabelByEntity(tbl.id)
	tbl.sitelink = mw.wikibase.getSitelink(qid)

	claimsAge = mw.wikibase.getBestStatements(qid, 'P4135' )
	--If P4135 (max age) set
	if next(claimsAge) then
		-- Read first value (should only have one value)
		tbl.age= string.sub(read(claimsAge[1],'amount'),2,-1)
	end
	return tbl
end

function getHeight(qid)
	--Height
	local wdHeight=mw.wikibase.getBestStatements(qid, 'P2048' )
	--Only show if set 
	local objOutput={}
	if next(wdHeight) then
		fHeight = string.sub(read(wdHeight[1],'amount'),2,-1)
		txtUnitWithInsaneURL= read(wdHeight[1],'unit') 
		indexSlash = txtUnitWithInsaneURL:match'^.*()/' -- Find last slash
		idUnitentity=string.sub(txtUnitWithInsaneURL,indexSlash+1) -- Just read after the last slash
		-- The code can currently only handle centimeters (Q174728) and meters (Q11573)
		-- It will show the height in centimeters. If the height is stored in meters it will be converted to centimeters.
		objOutput.bUnitok=false
		-- If unit is centimeter
		if (idUnitentity=="Q174728") then
			objOutput.bUnitok=true
			end
		-- If unit is meter
		if (idUnitentity=="Q11573") then				
			fHeight = fHeight * 100
			objOutput.bUnitok=true
		end
		objOutput.data=fHeight
		-- txtUnpackReference(frame,tblProcessAllRefsForItemWD(frame,wdHeight[1].references,entityid,'P2048')) ..  txtEditPen(entityid,'P2048');
		objOutput.bHasRef,objOutput.ref=processAllRefsForWDItem_model(wdHeight[1].references,qid,'P2048')
		objOutput.unit="cm"
		objOutput.qid=qid
		objOutput.pid='P2048'
		return objOutput
	end
	return nil
end

function getTeams(qid,pid)
	--Fill tables with information about the teams (club & national) that the person has played with or coached
	local teams = {}
    local claimClubs = mw.wikibase.getBestStatements(qid,pid)
    local key, value
    --Loop through all teams (clubs,national,other)
    for key, value in pairs( claimClubs ) do
    	local idTeam = read(value,'id')
    	local team={}
    	bIsClub=isClub( idTeam,'P31' )
    	bIsNationalTeam=isNationalTeam( idTeam,'P31')
    	-- If a sports club or a national team
		if (bIsClub or bIsNationalTeam) then
			team.from,team.to = readDates(value)  
			team.bHasRef,team.ref=processAllRefsForWDItem_model(value['references'],qid,value.id)
			team.qid=qid
			team.pid=value.id
			team.id=idTeam
			txtGenderSymbol=''
			if (pid=='P6087') then					-- Only check for different genders if coaching
				team.iGender = iGender(idTeam)
			end			
			if value['qualifiers'] then
				if value['qualifiers']['P1350'] then
					team.games=string.sub(readQualifier(value.qualifiers.P1350[1],'amount'),2,-1)
				end
				if (not team.games) and value['qualifiers']['P1129'] then
					team.games=string.sub(readQualifier(value.qualifiers.P1129[1],'amount'),2,-1)
				end
				if value['qualifiers']['P1351'] then
					team.goals=string.sub(readQualifier(value.qualifiers.P1351[1],'amount'),2,-1)
				end
				if value['qualifiers']['P641'] then
					sport=readQualifier(value.qualifiers.P641[1],'id')
					team.sports={sport}
					end
			end
			if (isempty(team.sports)) then
				local p641=mw.wikibase.getAllStatements(idTeam, 'P641' )
				sports={}
				for key2,value2 in pairs( p641 ) do
						sport=read(value2,'id')
						table.insert(sports,sport)
				end
				team.sports=sports
			end
		end

		team.isclub=false
		team.isnationalteam=false
		if bIsClub then    
			team.isclub=true
			if (team.from and team.from.year) then
				team.data=txtWikilink(idTeam,team.from.year)
				else
				team.data=txtWikilink(idTeam)
				end
		end
		if bIsNationalTeam then
			team.isnationalteam=true
			team.country=tblNationalTeamInfo(idTeam)
			-- Check if the national team has a set max age (i.e. if it is a junior team)
			-- If so there will be added an "(UXX)" after the nation, where XX is the max age
			if value['qualifiers'] then
				--Set number of appearances (if available) from P1129 (first priority) or P1350
				if value['qualifiers']['P1129'] then
					team.appearances=string.sub(readQualifier(value.qualifiers.P1129[1],'amount'),2,-1)
					else
					if value['qualifiers']['P1350'] then
						team.appearances=string.sub(readQualifier(value.qualifiers.P1350[1],'amount'),2,-1)
						else
						team.appearances=nil
						end
					end
				end
			end
		table.insert(teams,team)
	    end
--[=====[ 
--]=====]
	return teams
end

function getSportOccupation (qid)
	local claimOccupations=mw.wikibase.getBestStatements(qid, 'P106' )
	local sports={}
	local sports_ids={}
    for key, value in pairs( claimOccupations ) do
    	local sport={}
	    occupationid=read(value,'id')
		claimSport=mw.wikibase.getBestStatements(occupationid,'P641')
		if (claimSport[1]) then
		    sport.id=read(claimSport[1],'id')
		    if not isMember(sport.id,sports_ids) then -- Only add sport if not already added (for example through another occupation)
				sport.data=txtWikilink(sport.id)
				sport.data_plain=getLabelByEntity(sport.id)
				sport.bHasRef, sport.ref = processAllRefsForWDItem_model(value.references,qid,pid)
				sport.qid=qid
				sport.pid=value.id
				table.insert(sports_ids,sport.id)
				table.insert(sports,sport)
				end
			else
				-- Add some warning that no sport is set (though might make sense if has been active in other areas)
			end
    end
    return sports
end

-- Function to check if an item is in an array
function isMember(item, array)
    for _, value in ipairs(array) do
        if value == item then
            return true
        end
    end
    return false
end


function readFirstStatementFlexible(qid,pid,txtType)
	local statements=mw.wikibase.getBestStatements(qid,pid)
	if not(next(statements)==nil) then
		if not(statements[1]==nil) then
			local objOutput={}
			data=read(statements[1],txtType)
			if (txtType=='time') then
				objOutput.date=data
				local snak =statements[1].mainsnak
				objOutput.data=mw.wikibase.formatValue( snak )
				objOutput.precision=read(statements[1],'precision')
				else
				if (txtType=='id') and not (data==nil) then
					objOutput.data=mw.wikibase.getLabel(data)
					else
					objOutput.data=data
					end
				end
			objOutput.bHasRef,objOutput.ref=processAllRefsForWDItem_model(statements[1].references,qid,pid)
			objOutput.qid=qid
			objOutput.pid=pid
			return objOutput
			end
		end
	return nil
	end

showcountry=function(frame,tbl)
	if (tbl.country) then
		txtTitleShown=tbl.country.txtName 
		if (tbl.country.age) then
			 txtTitleShown=txtTitleShown .. ' (U' .. tbl.country.age .. ')'
		end
		if (tbl.country.bIsReserve) then
			 txtTitleShown=txtTitleShown .. ' (' .. txtReserveLabel .. ')'
		end
		if (tbl.country.sitelink) then
			txt= frame:expandTemplate{ title = txtFlagIconTemplate , args={tbl.country.txtName}} ..' [[' ..  tbl.country.sitelink .. '|' .. txtTitleShown .. ']]'
			else
			txt= frame:expandTemplate{ title = txtFlagIconTemplate , args={tbl.country.txtName}} ..' ' .. txtTitleShown
			end
		return txt
		else
		return ''
		end
end

function p.now()
    local currentDateStr = os.date("%Y-%m-%d %H:%M:%S")
    return currentDateStr
end

p.age=function(iStartYear,iStartMonth,iStartDay,iEndYear,iEndMonth,iEndDay)
	local iAge=iEndYear-iStartYear
	if (iStartMonth>iEndMonth) or ((iStartMonth==iEndMonth) and (iStartDay>iEndDay)) then
		iAge=iAge-1
	end
	return iAge
end

p.showage=function()
	if (p.alive) then 
		local ok_precision=p.birthdate.precision>=11
		if (ok_precision) then
			iBirthYear = tonumber(string.sub(p.birthdate.date,2,5))
			iBirthMonth = tonumber(string.sub(p.birthdate.date,7,8))
			iBirthDay = tonumber(string.sub(p.birthdate.date,10,11))
			local now=p.now()
			iNowYear = tonumber(string.sub(now,1,4))
			iNowMonth = tonumber(string.sub(now,6,7))
			iNowDay = tonumber(string.sub(now,9,10))
			iAge=p.age(iBirthYear,iBirthMonth,iBirthDay,iNowYear,iNowMonth,iNowDay)
     		 return ' (' .. iAge .. ' år)'
		end
	end
	return ''
end

p.showlifespan=function()
	if not (p.alive) then 
		local ok_precision=p.birthdate.precision>=11
		if (ok_precision) then
			iBirthYear = tonumber(string.sub(p.birthdate.date,2,5))
			iBirthMonth = tonumber(string.sub(p.birthdate.date,7,8))
			iBirthDay = tonumber(string.sub(p.birthdate.date,10,11))
			iDeathYear = tonumber(string.sub(p.deathdate.date,2,5))
			iDeathMonth = tonumber(string.sub(p.deathdate.date,7,8))
			iDeathDay = tonumber(string.sub(p.deathdate.date,10,11))
			iAge=p.age(iBirthYear,iBirthMonth,iBirthDay,iDeathYear,iDeathMonth,iDeathDay)
     		 return ' (' .. iAge .. ' år)'
		end
	end
	return ''
end

p.thirdcolumn=function(data)
	if (data) then
		local txt=''
		if (data.games) then
			txt = data.games
		end
		if (data.goals) then
			txt = txt .. ' (' .. data.goals .. ')'
			end
		return txt
		end
	return ''	-- return empty string if no data
end




-----------------------TO BE MOVED TO REFERENSHANTERING----------------
-- from: https://stackoverflow.com/questions/2421695/first-character-uppercase-lua
-- Works only for letters in the standard latin alphabet
function firstToUpper(str)
    -- Use pattern matching to find the first letter
    local first_letter = str:match("%a")
    
    if first_letter then
        -- Replace the first letter with its uppercase version
        local capitalized_str = str:gsub(first_letter, first_letter:upper(), 1)
        return capitalized_str
    else
        -- Return the original string if no letter is found
        return str
    end
end

--[=====[ 

-- Fills in the country/state an athlete competes for.
-- A reasonably large number of regions compete in international competitons without
-- being independent states (such as England, Scotland, Wales, Northern Ireland, Puerto Rico etc.)
-- Wikidata has a special property (P1532, country for sport) to handle such cases
-- This function therefore first read from there and if nothing is found use P17 (country)
function txtSportsCountry(iTeam)
	txtSportcountry=readFirstStatement(iTeam,'P1532')
	if (txtSportcountry==nil) then
		txtSportcountry=readFirstStatement(iTeam,'P17')
	end
	return txtSportcountry
end
--]=====]

--[=====[ 
--]=====]

return p