local tilemap = require("maskCollection/scripts/tilemap")

local npcManager = require("npcManager")

local birdo = {}
local npcID = NPC_ID


function birdo.onInitAPI()
	npcManager.registerEvent(npcID, birdo, "onTickNPC")
end


--[[local function blockIsSolid(block,v)
	if block.isHidden or block:mem(0x5A,FIELD_BOOL) then
		return
	end

	local config = Block.config[block.id]

	if config.passthrough then
		return false
	end

	if config.npcfilter < 0 or config.npcfilter == v.id then
		return false
	end

	if (config.semisolid or config.sizeable) and (v.y + v.height - 8) > block.y then
		return false
	end
	
	return true
end

local function cliffAtSpot(v,x,width)
	local collider = Colliders.Box(x,v.y + v.height - 4,width,20)

	for _,block in Block.iterateIntersecting(collider.x,collider.y,collider.x + collider.width,collider.y + collider.height) do
		if blockIsSolid(block,v) and collider:collide(block) then
			return false
		end
	end

	return true
end]]

local function cliffAtSpot(v,x,width)
	return tilemap.areaIsEmpty(x,v.y + v.height - 4,x + width,v.y + v.height + 16,true)
end

function birdo.onTickNPC(v)
	if Defines.levelFreeze then return end

	if v.despawnTimer <= 0 then
		return
	end

	-- Prevent Birdo from just walking into the abyss
	if v.collidesBlockBottom then
		if v.ai3 <= 200 and cliffAtSpot(v,v.x - 4,4) then
			v.ai3 = 201
		elseif (v.ai3 >= 250 and v.ai3 <= 450) and cliffAtSpot(v,v.x + v.width,4) then
			v.ai3 = 451
		end
	end
end


return birdo