--[[
			// GameJoin.lua

			// Handles game join logic
]]
local CoreGui = Game:GetService("CoreGui")
local GuiRoot = CoreGui:FindFirstChild("RobloxGui")
local Modules = GuiRoot:FindFirstChild("Modules")
local PlatformService = nil
pcall(function() PlatformService = game:GetService('PlatformService') end)

local Errors = require(Modules:FindFirstChild('Errors'))
local ErrorOverlayModule = require(Modules:FindFirstChild('ErrorOverlay'))
local ScreenManager = require(Modules:FindFirstChild('ScreenManager'))
local Utility = require(Modules:FindFirstChild('Utility'))

local GameJoin = {}

GameJoin.JoinType = {
	Normal = 0;			-- use placeId
	GameInstance = 1;	-- use game instance id
	Follow = 2;			-- use userId or user you are following
}

GameJoin.OnGameJoinSuccess = Utility.Signal()

local COOLDOWN = 1
local canJoinGame = true
if PlatformService then
	PlatformService.ViewChanged:connect(function(viewType)
		if viewType == 0 then
			wait(COOLDOWN)
			canJoinGame = true
		end
	end)
end

-- joinType - GameJoin.JoinType
-- joinId - can be a userId or placeId, see JoinType for which one to use
function GameJoin:StartGame(joinType, joinId)
	if not canJoinGame then return end
	--
	canJoinGame = false
	print("Starting game with joinType", joinType, "with joinId", joinId)
	if UserSettings().GameSettings:InStudioMode() then
		ScreenManager:OpenScreen(ErrorOverlayModule(Errors.Test.CannotJoinGame), false)
		canJoinGame = true
	elseif PlatformService then
		local success, result = pcall(function()
			return PlatformService:BeginStartGame3(joinType, joinId)
		end)
		if not success then
			ScreenManager:OpenScreen(ErrorOverlayModule(Errors.GameJoin[#Errors.GameJoin]), false)
			canJoinGame = true
		end
		if Errors.GameJoin[result] then
			ScreenManager:OpenScreen(ErrorOverlayModule(Errors.GameJoin[result]), false)
			canJoinGame = true
		end
		GameJoin.OnGameJoinSuccess:fire(success)
	end
end

return GameJoin
