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

local npcManager = require("npcManager")

local boomBoom = {}
local npcID = NPC_ID


function boomBoom.onInitAPI()
	npcManager.registerEvent(npcID, boomBoom, "onTickNPC")

	registerEvent(boomBoom, "onNPCHarm")
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 + 256,true)
end

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

	if v.despawnTimer <= 0 then
		return
	end

	-- Prevent Boom Boom from just walking into the abyss
	if v.collidesBlockBottom then
		if v.ai1 == 0 then
			if (v.direction == DIR_LEFT and cliffAtSpot(v,v.x - 4,4)) or (v.direction == DIR_RIGHT and cliffAtSpot(v,v.x + v.width,4)) then
				local speedX = v.speedX

				v.direction = -v.direction
				v.speedX = -speedX*0.5
			end
		elseif v.ai1 == 1 then
			if (v.direction == DIR_LEFT and cliffAtSpot(v,v.x - 4,4)) or (v.direction == DIR_RIGHT and cliffAtSpot(v,v.x + v.width,4)) then
				v.speedX = 0
			end
		end
	end
end


function boomBoom.onNPCHarm(eventObj,v,reason,culprit)
	if v.id ~= npcID then
		return
	end

	-- Make Boom Boom more vulnerable to HARM_TYPE_NPC, by treating it like HARM_TYPE_SWORD instead
	if reason == HARM_TYPE_NPC then
		v:harm(HARM_TYPE_SWORD)
		eventObj.cancelled = true
	end
end


return boomBoom