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

local npcManager = require("npcManager")

local mouser = {}
local npcID = NPC_ID


function mouser.onInitAPI()
	npcManager.registerEvent(npcID, mouser, "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 mouser.onTickNPC(v)
	if Defines.levelFreeze then return end

	if v.despawnTimer <= 0 then
		return
	end

	-- Prevent Mouser from just walking into the abyss (much less likely than with Birdo, but still worth accounting for)
	if v.collidesBlockBottom then
		if (v.ai2 == DIR_LEFT and cliffAtSpot(v,v.x - 4,4)) or (v.ai2 == DIR_RIGHT and cliffAtSpot(v,v.x + v.width,4)) then
			v.ai2 = -v.ai2
		end
	end
end


return mouser