local p = {}
local Navbox = require("Module:Navbox")
local Uses_Wikidata = require("Module:Uses_Wikidata")._usestable

local title = mw.title.getCurrentTitle()
local namespace = title.namespace

local props = {}
local props2 = {}

local i8 = {
	["tracking"] = "[[تصنيف:معرفات الأصنوفة]]",
	["without"] = "[[تصنيف:معرفات الأصنوفة غير موجودة]]",
	["g1"] = "[[d:Wikidata:WikiProject_Taxonomy|معرفات الأصنوفة]]",
	["g2"] = "",
	["name"] = "Taxonomy text"
}

function make_url(url, label)
	url = mw.ustring.gsub(url, '%[', "%%5B")
	url = mw.ustring.gsub(url, '%]', "%%5D")
	
	label = mw.ustring.gsub(label, '%[', "[")
	label = mw.ustring.gsub(label, '%]', "]")
	return '[' .. url .. ' ' .. label .. ']'
end

function make_line(label, link)
	if link then
		if label then
			return '* <b>' .. label .. "</b>: " .. link .. "\n"
		else
			return "* " .. link .. "\n"
		end
	end
end

function doo(params)
	-- {property="P11", label = "", link = "", pattern = "https://www.gbif.org/species/$1" }

	local pa = params.label
	if params.link ~= "" then
		pa = "[[" .. params.link .. "|" .. pa .. "]]"
	end
	local po = {}
	local ids = params.ids or {}
	if #ids > 0 then
		local url = ''
		local n = 0
		for _, id in ipairs(ids) do
			n = n + 1
			-- match if id is url
			if string.match(id, "^https?://") then
				url = make_url(id, n)
			elseif params.pattern ~= '' then
				url = make_url(mw.ustring.gsub(params.pattern, '%$1', id), id)
			else
				url = id
			end
		end
		table.insert(po, url)
		--break
	end

	local va = ''
	local po_text = mw.text.listToText(po, "، ", "، ")
	if po_text and po_text ~= "" then
		va = make_line(pa, po_text)
	end
	return va
end

function getIdsFromWikidata(qid, property)
	local ids = {}
	for _, statement in ipairs(mw.wikibase.getBestStatements(qid, property)) do
		if statement.mainsnak.datavalue then
			local val = statement.mainsnak.datavalue.value
			if val then
				table.insert(ids, val)
			end
		end
	end
	mw.log(property .. " lenth: " .. #ids)
	return ids
end

function makeSections(qid, args, Table)
	local tval = {}
	-- { property = "P846", label = "المَرفَق العالمي لمعلومات التنوع الحيوي (GBIF)", link = "مرفق معلومات التنوع الحيوي العالمي", pattern = "https://www.gbif.org/species/$1" }
	for property, params in pairs(Table) do
		local ids = getIdsFromWikidata(qid, property)
		if #ids == 0 and args[property] then
			table.insert(ids, args[property])
		end
		params.ids = ids
		params.property = property
		tval[property] = params
	end

	local external = {}
	for pid, params in pairs(tval) do
		if #params.ids > 0 then
			local vaa = doo(params)
			table.insert(external, vaa)
		end
	end
	local final = table.concat(external)
	if #final ~= 0 then
		final = final .. i8.tracking
	end
	return final
end

function Statement(options)
	local function resolveQID(qid)
		if qid and qid ~= "" then
			qid = 'Q' .. mw.ustring.gsub(qid, '^[Qq]', '')
			if mw.wikibase.isValidEntityId(qid) and mw.wikibase.entityExists(qid) then
				local sitelink = mw.wikibase.getSitelink(qid)
				if sitelink then
					return mw.wikibase.getEntityIdForTitle(sitelink) or mw.wikibase.getEntity(qid).id
				end
				return mw.wikibase.getEntity(qid).id
			end
		end
	end

	local qid = options.entityId or options.id or options["صفحة"] or ''
	if namespace == 0 then
		qid = mw.wikibase.getEntityIdForCurrentPage()
	end
	local qid = resolveQID(qid)

	if not qid then
		return i8.without
	end
	mw.log('qid' .. qid)
	local text2 = ""
	local text = makeSections(qid, options, props) or ""
	if props2 and props2 ~= {} then
		text2 = makeSections(qid, options, props2) or ""
	end
	local params = {
		name = i8.name,
		bodyclass = "hlist",
		list1style = "text-align:right;",
		list2style = "text-align:right;",
		group1 = i8.g1,
		group2 = i8.g2
	}
	if options.nohlist and options.nohlist ~= '' then params.bodyclass = '' end
	local fi = ''
	if (text and text ~= "") or (text2 and text2 ~= "") then
		if text and text ~= "" then
			if options.list and options.list ~= "" then
				text = text .. options.list
			end
			params.list1 = text
		end
		if text2 and text2 ~= "" then
			params.list2 = text2
		end
		fi = Navbox._navbox(params)
	else
		fi = i8.without
	end
	return fi
end

function p.Statement_from_lua(options, _i8, _props, _props2)
	i8 = _i8
	props = _props
	props2 = _props2
	return Statement(options)
end

function p.make_list(props)
	local _tab_ = {}
	for k, v in pairs(props) do
		table.insert(_tab_, k)
	end
	_tab_.newtrak = "s"
	_tab_["newtrak"] = "s"
	return Uses_Wikidata(_tab_)
end

function p.list(frame)
	return p.make_list(props)
end

return p