local p = {};

local function checklayer(depth) -- check subclasses of items at current depth
	checklist[depth+1] = {} -- setup next layer of table
	local j = 0
	for j = 1,#checklist[depth] do -- loop over items at current depth
		local property
		if depth == 1 then
			property = "P31" -- use P31 for depth 1
		else
			property = "P279" -- use P279 for depths 2+
		end
		local subclasses = mw.wikibase.getBestStatements(checklist[depth][j],property) -- get P31 or P279 statements
		for i,statement in ipairs(subclasses) do -- loop through items at next depth
			if statement.mainsnak.snaktype == 'value' then
				local newitem = statement.mainsnak.datavalue.value.id
				if newitem == value then
					isInstance = true
				else
					checklist[depth+1][#checklist[depth+1]+1] = newitem -- add item to next depth of checklist table
				end
			end
		end
	end
	return isInstance
end

function p.main(frame)
	local args = frame.args
	local pargs = frame:getParent().args
	value = args.value or pargs.value
	local qid = args.qid or pargs.qid or ""
	if qid == "" then
		qid = mw.wikibase.getEntityIdForCurrentPage()
	end
	if not qid then
		return 0
	end
	checklist = {{qid}}
	local md = args.maxdepth or pargs.maxdepth
	if md then
		maxdepth = tonumber(md)
	else
		maxdepth = 5
	end
	depth = 0 -- current depth
	isInstance = false -- assume false until match found
	while not isInstance and depth<maxdepth do
		depth = depth+1
		checklayer(depth)
	end
	if not isInstance then
		depth = 0 -- indicates not isInstance
	end
	return depth -- return depth that item was found
end

return p