-- *** Example spawning car ***
-- Since: v0.4.1
-- 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 new_obj = 0
local index = 1
local ped = 0 

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(100)
			for i = 1, 6, 1 do
				ped = GetPedStruct(i)
				x, y, z = GetPedPos(ped)
				if (GetPedRangeOfPoint(ped, x, y, z) <= 0.5) then
					 --WriteInLog(string.format("ped index %d id %d struct %X\n",i,GetPedID(ped),ped))
					 break
				end
			end
			gamestate = 1
		else
			if (ped ~= 0) then		
				if (IsKeyDown(0x37)) then -- Down key "7" for prev obj
					local x, y, z = GetPedPos(ped)	
					STAGEC.DeleteObj(new_obj)
					wait(50)
					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 struct %X\n", index, GetObjModel(new_obj), 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)
					wait(50)
					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 struct %X\n", index, GetObjModel(new_obj), new_obj))
					index = index + 1
					if (index > #Obj.VALID_OBJ_MODEL) then
						index = #Obj.VALID_OBJ_MODEL
					end	
				end					
			end
		end
	else
		wait(100)
		gamestate = 0 -- If not frame to game restart or game not loaded
	end
end