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

local npcManager = require("npcManager")

local larry = {}
local npcID = NPC_ID


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

	if v.despawnTimer <= 0 then
		return
	end

	if v.ai1 == 0 then -- Normal, walking state
		-- Jump at cliffs
		if v.collidesBlockBottom and cliffAtSpot(v,v.x + v.width*0.5 - 2,4) then
			v.ai3 = 150
		end

		-- Jump less frequently
		v.ai3 = v.ai3 - 0.25

		-- Shoot magic less frequently
		v.ai4 = v.ai4 - 0.5
	elseif v.ai1 == 1 then -- Pre-firing state
		-- Take slightly longer to shoot
		v.ai3 = v.ai3 - 0.5
	end
end


return larry