-- *** Example spawning car ***
-- Since: v0.4.1
-- Make new car 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 Car = require("modules.car")

local gamestate = 0
local new_car = 0
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(0x31)) then -- Down key "1" for add car
					local x, y, z = GetPedPos(ped)		
					new_car = STAGEC.CreateCar(x + 2, y, z, GetPedAngle(ped), 11, 65535, 65535, 1) -- Create tank
					WriteInLog(string.format("Spawning car id %d struct %X name %s\n", GetCarID(new_car), new_car, Car.GetCarName(new_car)))
				end
				if (IsKeyDown(0x32)) then -- Down key "2" for delete car
					STAGEC.DeleteCar(new_car) -- Delete car
				end					
			end
		end
	else
		wait(100)
		gamestate = 0 -- If not frame to game restart or game not loaded
	end
end