local onlinePlayNPC = require("scripts/onlinePlay_npc")

local battleGeneral = require("scripts/battleGeneral")

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

local billy = {}
local npcID = NPC_ID

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


local function getTimer(v)
	local settings = v.data._settings

	if (settings.projectile ~= 0 and settings.projectile ~= 17) or settings.timer ~= 20 then
		return v.data._basegame.timer
	else
		return v.ai1
	end
end

function billy.onTickNPC(v)
	local data = v.data

	if v.despawnTimer <= 0 then
		data.oldTimer = nil
		data.vanishTimer = nil
		data.shotsLeft = nil
		return
	end
	
	local settings = v.data._settings

	local timer = getTimer(v)

	if data.oldTimer == nil then
		data.oldTimer = timer

		if settings.shots > 0 then
			data.shotsLeft = settings.shots
		else
			data.shotsLeft = math.huge
		end

		data.vanishTimer = 0
	end

	if data.shotsLeft <= 0 then
		data.vanishTimer = data.vanishTimer + 1

		if data.vanishTimer >= 48 then
			-- Poof out of existance
			Effect.spawn(10,v.x + v.width*0.5 - 16,v.y + v.height*0.5 - 16)
			onlinePlayNPC.forceKillNPC(v,HARM_TYPE_VANISH)
		end

		-- Disable shooting
		v.data._basegame.timer = 0
		v.ai1 = 0

		return
	else
		data.vanishTimer = 0
	end

	if timer == 0 and data.oldTimer > timer then
		data.shotsLeft = data.shotsLeft - 1
	end

	data.oldTimer = timer
end


function billy.onCameraDrawNPC(v,camIdx)
	if v.despawnTimer <= 0 or v:mem(0x12C,FIELD_WORD) <= 0 then
		return
	end

	local settings = v.data._settings
	local data = v.data

	if settings.shots <= 0 or data.shotsLeft == nil then
		return
	end

	battleGeneral.drawProgressCircle{
		progress = data.shotsLeft/settings.shots,
		
		priority = -0.1,sceneCoords = true,

		x = v.x + v.width*0.5,
		y = v.y - 40,
	}
end


onlinePlayNPC.onlineHandlingConfig[npcID] = {
	getExtraData = function(v)
		local data = v.data

		return {
			clownCarTimer = data._basegame.clownCarTimer,
			timer = data._basegame.timer,

			shotsLeft = data.shotsLeft,
			vanishTimer = data.vanishTimer,
			oldTimer = data.timer,
		}
	end,
	setExtraData = function(v,receivedData)
		local data = v.data

		data._basegame.clownCarTimer = receivedData.clownCarTimer or data._basegame.clownCarTimer
		data._basegame.timer = receivedData.timer or data._basegame.timer

		data.shotsLeft = receivedData.shotsLeft or data.shotsLeft
		data.vanishTimer = receivedData.vanishTimer or data.vanishTimer
		data.oldTimer = receivedData.oldTimer or data.oldTimer
	end,
}


return billy