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

local onlinePlay = require("scripts/onlinePlay")
local onlinePlayPlayers = require("scripts/onlinePlay_players")

local ai = require("scripts/booMushroom")


local booMushroom = {}
local npcID = NPC_ID

local booMushroomSettings = {
	id = npcID,
	
	gfxwidth = 0,
	gfxheight = 0,

	gfxoffsetx = 0,
	gfxoffsety = 2,
	
	width = 32,
	height = 32,
	
	frames = 1,
	framestyle = 0,
	framespeed = 8,
	
	speed = 1,
	
	npcblock = false,
	npcblocktop = false, --Misnomer, affects whether thrown NPCs bounce off the NPC.
	playerblock = false,
	playerblocktop = false, --Also handles other NPCs walking atop this NPC.

	nohurt = false,
	nogravity = false,
	noblockcollision = false,
	nofireball = false,
	noiceball = false,
	noyoshi = false,
	nowaterphysics = false,
	
	jumphurt = false,
	spinjumpsafe = false,
	harmlessgrab = false,
	harmlessthrown = false,

	isinteractable = true,

	maxSpeed = 1.8,
	deceleration = 0.05,


	effectDuration = lunatime.toTicks(15),
}

npcManager.setNpcSettings(booMushroomSettings)
npcManager.registerHarmTypes(npcID,{},{})

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

	registerEvent(booMushroom, "onPostNPCCollect")
	registerEvent(booMushroom, "onTick")
end

function booMushroom.onTickNPC(v)
	if Defines.levelFreeze or v.despawnTimer <= 0 then
		return
	end

	local config = NPC.config[v.id]

	-- Mushroom movement
	if v.direction == 0 then
		local p = npcutils.getNearestPlayer(v)

		v.direction = -p.direction
	end

	if v.speedX > config.maxSpeed then
		v.speedX = math.max(config.maxSpeed,v.speedX - confg.deceleration)
	elseif v.speedX < -config.maxSpeed then
		v.speedX = math.min(-config.maxSpeed,v.speedX + config.deceleration)
	elseif not v:mem(0x136,FIELD_BOOL) then
		v.speedX = config.maxSpeed*v.direction
	end
end


function booMushroom.onPostNPCCollect(v,p)
	if v.id ~= npcID then
		return
	end

	if not onlinePlayPlayers.ownsPlayer(p) then
		-- Ignore if we weren't the one to collect it
		return
	end

	local config = NPC.config[v.id]

	ai.start(p,config.effectDuration)
end


return booMushroom