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

local basic3DWorld = require("basic3DWorld")
local lib3d = require("lib3d")

local easing = require("ext/easing")


local emerald = {}
local npcID = NPC_ID


function emerald.onInitAPI()
	npcManager.registerEvent(npcID, emerald, "onDrawNPC")
end


local texture = Graphics.loadImageResolved("npc-".. npcID.. "-main.png")
local material = lib3d.Material(nil,{texture = texture},{},{UNLIT = true,TONEMAP = false,ALPHAMODE = lib3d.macro.ALPHA_CUTOFF})

local function initialise(v,data,config)
	data.initialized = true

	-- Model
	if not basic3DWorld.useSimpleMode() and (data.mesh == nil or not data.mesh.isValid) then
		data.mesh = lib3d.Quad{width = texture.width,height = texture.height,material = material}
	end
end


local activeNPCs = {}

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

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

	if not data.initialized then
		initialise(v,data,config)
	end

	if not basic3DWorld.useSimpleMode() then
		if not data.isActive then
			table.insert(activeNPCs,v)
			data.isActive = true
		end

		npcutils.hideNPC(v)

		return
	end
end


function basic3DWorld.onPreDraw(camIdx,camera3D)
	local time = lunatime.tick()/64
	local rotation = easing.inOutSine(time % 1,0,180,1) + 180*(math.floor(time)%2)
	local rotationQuat = vector.quat(0,rotation,0)

	for i = #activeNPCs,1,-1 do
		local v = activeNPCs[i]
		local data = v.data

		if v.isValid and v.despawnTimer > 0 and data.isActive then
			local mesh = data.mesh

			mesh.transform.position = vector(v.x + v.width*0.5,v.y + v.height*0.5,-16)
			mesh.transform.rotation = rotationQuat
			mesh.active = true
		else
			data.isActive = false
			table.remove(activeNPCs,i)
		end
	end
end

function basic3DWorld.onPostDraw(camIdx,camera3D)
	for _,v in ipairs(activeNPCs) do
		local data = v.data

		data.mesh.active = false
	end
end


return emerald