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

local npcManager = require("npcManager")

local wart = {}
local npcID = NPC_ID


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


local bubbleShots = 6
local bubbleSpeed = -7


--[[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 wart.onTickNPC(v)
	if Defines.levelFreeze then return end

	if v.despawnTimer <= 0 then
		return
	end

	-- Prevent Wart from just walking into the abyss
	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

	if v.ai1 == 1 then
		-- Remove the RNG from the speed of bubbles
		for _,npc in NPC.iterateIntersecting(v.x,v.y,v.x + v.width,v.y + v.height) do
			if npc.id == 202 and not npc.isGenerator and not npc.isHidden and npc.despawnTimer > 0 then
				if not npc.data.changedSpeed then
					npc.data.changedSpeed = true
					npc.speedY = bubbleSpeed
				end
			end
		end

		-- Always make sure to finish as early as possible
		if v.ai3 >= (bubbleShots*10) then
			v.ai1 = 0
			v.ai3 = 0
		end
	end
end


return wart