local battlePlayer = require("scripts/battlePlayer")

local npcManager = require("npcManager")

local smb3Bowser = {}
local npcID = NPC_ID


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


local function getClosestActivePlayer(x,y,biasedPlayer)
    local closestSquareDistance = math.huge
    local closestPlayer = player

    for _,p in ipairs(battlePlayer.getActivePlayers()) do
        local distX = p.x + p.width*0.5 - x
        local distY = p.y + p.height*0.5 - y

		if p == biasedPlayer then
			distX = distX*0.5
			distY = distY*0.5
		end

        local squareDistance = distX*distX + distY*distY

        if squareDistance < closestSquareDistance then
            closestSquareDistance = squareDistance
            closestPlayer = p
        end
    end

    return closestPlayer
end


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

	local data = v.data

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

	if not data.initialised then
		data.targetPlayer = getClosestActivePlayer(v.x + v.width*0.5,v.y + v.height*0.5)
		data.initialised = true
	else
		data.targetPlayer = getClosestActivePlayer(v.x + v.width*0.5,v.y + v.height*0.5,data.targetPlayer)
	end

	v.ai5 = data.targetPlayer.idx
end


return smb3Bowser