local getArgs = require('وحدة:Arguments').getArgs
local illWd = require('وحدة:Ill-wd')
local StringUtils = require('وحدة:StringUtils')
local wikidata = require('وحدة:Wikidata')
local clubData = mw.loadData('وحدة:نادي كرة قدم/data')
local p = {}

local prependToString = StringUtils._prependToString

local DEFAULT_FLAG = 'Flag of None.svg'

p.byItemFromArgs = function(itemId)
	local teamData = {}
	local teamDataRO = {}
	if itemId ~= nil and mw.ustring.match(itemId, 'Q%d+') then
		teamDataRO = clubData.teams[itemId] or {}
		teamData.linkTo = mw.wikibase.sitelink(itemId) or mw.wikibase.getEntity(itemId):getSitelink('enwiki') or teamDataRO.roLabel
	else
		teamData.linkTo = nil
	end
	teamData.flag = teamDataRO.flag or DEFAULT_FLAG
	teamData.roLabel = teamDataRO.roLabel
	
	
	local wikitext = ''
	local teamLink = ''

	if teamData.linkTo then
		if StringUtils._startsWith({teamData.linkTo, '[['}) then
			teamLink = teamData.linkTo
		else
			local teamLinkTitle = mw.title.new(teamData.linkTo, '')
			if teamLinkTitle.exists then
				teamLink = '[[' .. teamData.linkTo .. prependToString({teamData.roLabel, '|'}) .. ']]'
			else
				teamLink = illWd.fromArgs(itemId, teamData.roLabel, teamData.linkTo)
			end
		end
	else
		if itemId ~= nil and mw.ustring.match(itemId, 'Q%d+') then
			teamLink = illWd.fromArgs(itemId, teamData.roLabel, teamData.roLabel)
		else 
			teamLink = itemId
		end
	end
	
	local flagName = teamData.flag or DEFAULT_FLAG
	wikitext = wikitext .. '[[ملف:' .. flagName .. '|23px|border]] '
	local nowrapspan = mw.html.create('span'):css('white-space', 'nowrap'):wikitext(teamLink)
	wikitext = wikitext .. tostring(nowrapspan)
	return wikitext
end

p.byKeyFromArgs = function(key)
	local entityId = clubData.entities[key or '']
	return p.byItemFromArgs(entityId or key)
end

p.byKeyFromFrame = function(frame)
	local args = getArgs(frame)
	local key = args[1]
	return p.byKeyFromArgs(key)
end

return p