--Used by [[Template:IsPartOf]]
local title = tostring(mw.title.getCurrentTitle())
local entity = mw.wikibase.getEntityObject()
function suggest(pid)
	if entity and entity.claims and entity.claims[pid] then
		local qid = entity.claims[pid][1].mainsnak.datavalue.value["numeric-id"]
     	local link = mw.wikibase.sitelink("Q" .. qid)
     	if link and link ~= title then return link else return nil end
	end
	return nil
end

local p = {}

function p.suggest(frame)
	if frame:getParent().args[1] == nil or frame:getParent().args[1] == '' then
		return suggest("P131") or suggest("P17") or suggest("P30") or ''
	else
		if mw.title.new( frame:getParent().args[1], 0 ).exists then
			return frame:getParent().args[1]
		else
			return suggest("P131") or suggest("P17") or suggest("P30") or frame:getParent().args[1]
		end
	end	
end
function p.autocreate(frame)
	local content=mw.title.makeTitle( 0, mw.title.getCurrentTitle().text ):getContent()
	local place=frame:getParent().args[1]
	if place=='' then
		place=nil
	end
	if content and not place then
		content=mw.ustring.gsub( content, "isPartOf", "IsPartOf")
		content=mw.ustring.gsub( content, "ispartof", "IsPartOf")
		content=mw.ustring.gsub( content, "Ispartof", "IsPartOf")
		content=mw.ustring.gsub( content, "IsIn", "IsPartOf")
		content=mw.ustring.gsub( content, "isIn", "IsPartOf")
		content=mw.ustring.gsub( content, "Isin", "IsPartOf")
		content=mw.ustring.gsub( content, "isin", "IsPartOf")
		content=mw.ustring.gsub( content, "Partof", "IsPartOf")
		content=mw.ustring.gsub( content, "partof", "IsPartOf")
		content=mw.ustring.gsub( content, "位于", "IsPartOf")
		content=mw.ustring.gsub( content, "位於", "IsPartOf")
		content=mw.ustring.gsub( content, "处于", "IsPartOf")
		content=mw.ustring.gsub( content, "處於", "IsPartOf")
		if mw.ustring.find(content, "{{IsPartOf}}", 1, true) then
			--wait for T74815
		elseif  mw.ustring.find(content, "{{IsPartOf|", 1, true) then
			content=mw.ustring.sub( content,mw.ustring.find(content, "{{IsPartOf|", 1, true)+11)
			place=mw.ustring.sub( content,1,mw.ustring.find(content, "}}", 1, true)-1)
		end
	end
	if place then
		return '{{IsPartOf|'..place..'}}'
	else
		return '{{IsPartOf/error}}'
	end
end
 
return p