local npcManager = require("npcManager")
local npcutils = require("npcs/npcutils")

local onlinePlayNPC = require("scripts/onlinePlay_npc")

local fallingLog = {}
local npcID = NPC_ID

local fallingLogSettings = {
	id = npcID,

	gfxwidth = 64,
	gfxheight = 32,

	width = 64,
	height = 32,

	gfxoffsetx = 0,
	gfxoffsety = 0,

	frames = 2,
	framestyle = 0,
	framespeed = 8,

	luahandlesspeed = true,
	nowaterphysics = true,
	cliffturn = false,
	staticdirection = true,

	npcblock = false,
	npcblocktop = true,
	playerblock = false,
	playerblocktop = true,

	nohurt = true,
	nogravity = true,
	noblockcollision = true,
	notcointransformable = true,
	nofireball = true,
	noiceball = true,
	noyoshi = true,

	jumphurt = false,
	spinjumpsafe = false,
	harmlessgrab = true,
	harmlessthrown = true,
	nowalldeath = false,

	ignorethrownnpcs = true,
}

npcManager.setNpcSettings(fallingLogSettings)


function fallingLog.onInitAPI()
	npcManager.registerEvent(npcID, fallingLog, "onTickNPC")
	npcManager.registerEvent(npcID, fallingLog, "onDrawNPC")

	registerEvent(fallingLog, "onDraw")
end


local function initialise(v)
	local config = NPC.config[v.id]
	local data = v.data

	data.opacity = 0

	data.initialised = true
end


local function isInsideBlocks(v)
	local topCollider = Colliders.Box(v.x,v.y + v.speedY,v.width,2)

	return (#Colliders.getColliding{a = topCollider,b = Block.SOLID,btype = Colliders.BLOCK} > 0)
end


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

	local data = v.data

	if v.despawnTimer <= 0 then
		data.initialised = false
		return
	end

	local config = NPC.config[v.id]

	if not data.initialised then
		initialise(v)
	end

	if v.forcedState == NPCFORCEDSTATE_NONE then
		-- Accelerate
		v.speedY = math.min(2,v.speedY + 0.05)

		-- Die if it's below the section bounds, or is inside of a block
		if onlinePlayNPC.ownsNPC(v) and (v.y > (v.sectionObj.boundary.bottom + 64) or isInsideBlocks(v)) then
			v:kill(HARM_TYPE_VANISH)
		end
	elseif v.forcedState == NPCFORCEDSTATE_WARP then
		if v.forcedCounter2 == 1 then
			-- Come out of warps slightly slower
			v.y = v.y + 0.75
		end

		data.opacity = math.min(1,data.opacity + 0.1)
	end

	-- Keep logs spawned forever
	v.despawnTimer = math.max(v.despawnTimer,100)

	--Text.print(string.format("%.2f",v.speedY),v.x - camera.x,v.y - camera.y)
end

function fallingLog.onDrawNPC(v)
	if v.despawnTimer <= 0 then
		return
	end

	local config = NPC.config[v.id]
	local data = v.data

	if not data.initialised then
		initialise(v)
	end

	local priority = (v.forcedState == NPCFORCEDSTATE_WARP and -96) or -66

	npcutils.drawNPC(v,{priority = priority,opacity = data.opacity})
	npcutils.hideNPC(v)
end


function fallingLog.onDraw()
	-- Make log generators always be active
	for _,v in NPC.iterate(npcID) do
		if v.isGenerator and not v.isHidden then
			v:mem(0x74,FIELD_BOOL,true)
		end
	end
end


return fallingLog