-- *** Example spawning car ***
-- Since: v0.4.2
-- Make new obj is area player.

-- Don't require from directory scripts it need load from special folder modules or other folder
local STAGEC = require("modules.STAGEC")
local Obj = require("modules.obj")

local gamestate = 0
local ped_pool = {}
local new_obj = 0
local index = 1

while (GetGameFrame() == 0) do 
end -- Wait update frame
if (GetSCRName() ~= "data/STAGEC.SCR") then
	SetSCRName("data/STAGEC.SCR") -- Load STAGEC.SCR (Stage Constructor)
end

while (true) do	
	wait(0)
	if (GetGameFrame() > 0) then
		if (gamestate == 0) then -- If start new game
			wait(50)
			for i = 1, 6 do
				ped_pool[i] = GetPedStruct(i)
			end
			if (#ped_pool > 0) then
				gamestate = 1
			end
		else
			if (gamestate == 1) then
				for i,ped in ipairs(ped_pool) do	
					if (IsKeyDown(0x37)) then -- Down key "7" for prev obj
						local x, y, z = GetPedPos(ped)	
						STAGEC.DeleteObj(new_obj)
						new_obj = STAGEC.CreateObj(x + 1, y, z, GetPedAngle(ped), Obj.VALID_OBJ_MODEL[index], 0, 1)
						WriteInLog(string.format("Spawning obj index %d model %d name %s struct %X\n", index, GetObjModel(new_obj), Obj.OBJ_NAME[Obj.VALID_OBJ_MODEL[index]], new_obj))
						index = index - 1
						if (index < 1) then
							index = 1
						end
					end
					if (IsKeyDown(0x38)) then -- Down key "8" for next obj
						local x, y, z = GetPedPos(ped)	
						STAGEC.DeleteObj(new_obj)
						new_obj = STAGEC.CreateObj(x + 1, y, z, GetPedAngle(ped), Obj.VALID_OBJ_MODEL[index], 0, 1)
						WriteInLog(string.format("Spawning obj index %d model %d name %s struct %X\n", index, GetObjModel(new_obj), Obj.OBJ_NAME[Obj.VALID_OBJ_MODEL[index]], new_obj))
						index = index + 1
						if (index > #Obj.VALID_OBJ_MODEL) then
							index = #Obj.VALID_OBJ_MODEL
						end	
					end					
				end
			end
		end
	else
		gamestate = 0 -- If not frame to game restart or game not loaded
	end
end