Documentation[créer] [purger]
local p = {}
local wd = require "Module:Wikidata"
local function categorize(wikipediavalue, wikidatavalue, catbase)
    if not wikidatavalue then
        return "[[Category:" .. catbase .. " absent de Wikidata]]"
    end
    if not wikipediavalue then
         return "[[Category:" .. catbase .. " fourni par Wikidata]]"
	end
	if wikipediavalue == wikidatavalue then
        return "[[Category:" .. catbase .. " identique sur Wikidata]]" -- yay!
	end
	return "[[Category:" .. catbase .. " différent sur Wikidata]]" -- needs human review :(
end

local function wikidatacheck(wikipediavalue, wikidatavalue, catbase, namespaces)
    -- exit if cat disabled in this namesapce
    local ok = false -- one-way flag to check if we're in a good namespace
    local ns = mw.title.getCurrentTitle().namespace
    for v in mw.text.gsplit( namespaces, ",", true) do
        if tonumber(v) == ns then
            ok = true
        end
    end
    if not ok then -- not in one of the approved namespaces
        return ""
    end
	return categorize(wikipediavalue, wikidatavalue, catbase)
end

function p.wikidatacheck(frame)
	local args= frame.args
	local namespaces = args.namespaces
	local wikipediavalue = args.value
	local property = args.property
	local catbase = args.category
	local wikidatavalue = wd.formatStatements({item= item, property=property})
	return wikidatacheck(wikipediavalue, wikidatavalue, catbase, namespaces)
end

function p.checkedlink(frame)
	local args = {}
	for i, j in pairs(frame.args) do
		if j ~= '' then args[i] = j end
	end
	
	local property = args.property
	local entity =args.item
	local namespaces = args.namespaces or '0'
	local wikipediavalue = args.id
	local basecatname = args.category
	local url = args.url

	local sitename = args.website
	if sitename then
		sitename = ' sur ' .. sitename
	else 
		sitename = ''
	end
	
	local accessdate = args.accessdate
	if accessdate then
		accessdate = ', consulté le ' .. accessdate
	else 
		accessdate = ''
	end
	
	local wikidatavalue	
	if property then 
		wikidatavalue = wd.formatStatements({entity =item, property = property})
	end
	
	local val = wikipediavalue or wikidatavalue
	if not val then
		return nil
	end
	local title = args.title
	if not title then
		title = 'entrée '.. val
	end	

	local link = mw.ustring.gsub(url, '$1', val)

	local realcat = ''
	if property and basecatname then
		realcat = categorize(wikipediavalue, wikidatavalue, basecatname)
	end

	return '[' .. link .. ' ' .. title .. ']' .. sitename .. accessdate .. '.', realcat
end

return p