--[[ Touch Events ]]
--
UserInputService.Changed:connect(function(property)
	if property == 'ModalEnabled' then
		IsModalEnabled = UserInputService.ModalEnabled

		if lastInputType == Enum.UserInputType.Touch then
			if ControlState.Current == ControlModules.Touch and IsModalEnabled then
				ControlState:SwitchTo(nil)
			elseif ControlState.Current == nil and not IsModalEnabled then
				ControlState:SwitchTo(ControlModules.Touch)
			end
		end
	end
end)

if FFlagUserNoCameraClickToMove then
	BindableEvent_OnFailStateChanged = MasterControl:GetClickToMoveFailStateChanged()
end
if BindableEvent_OnFailStateChanged then
	BindableEvent_OnFailStateChanged.Event:connect(function(isOn)
		if lastInputType == Enum.UserInputType.Touch and ClickToMoveTouchControls then
			if isOn then
				ControlState:SwitchTo(ClickToMoveTouchControls)
			else
				ControlState:SwitchTo(nil)
			end
		end
	end)
end

local switchToInputType = function(newLastInputType)
	lastInputType = newLastInputType

	if VRService.VREnabled then
		ControlState:SwitchTo(ControlModules.VRNavigation)
		return
	end

	if lastInputType == Enum.UserInputType.Touch then
		ControlState:SwitchTo(ControlModules.Touch)
	elseif lastInputType == Enum.UserInputType.Keyboard or
		lastInputType == Enum.UserInputType.MouseButton1 or
		lastInputType == Enum.UserInputType.MouseButton2 or
		lastInputType == Enum.UserInputType.MouseButton3 or
		lastInputType == Enum.UserInputType.MouseWheel or
		lastInputType == Enum.UserInputType.MouseMovement  then
		ControlState:SwitchTo(ControlModules.Keyboard)
	elseif lastInputType == Enum.UserInputType.Gamepad1 or
		lastInputType == Enum.UserInputType.Gamepad2 or
		lastInputType == Enum.UserInputType.Gamepad3 or
		lastInputType == Enum.UserInputType.Gamepad4 then
		ControlState:SwitchTo(ControlModules.Gamepad)
	end
end

if IsTouchDevice then
	createTouchGuiContainer()
end

MasterControl:Init()

UserInputService.GamepadDisconnected:connect(function(gamepadEnum)
	local connectedGamepads = UserInputService:GetConnectedGamepads()
	if #connectedGamepads > 0 then return end

	if not VRService.VREnabled then
		if UserInputService.KeyboardEnabled then
			ControlState:SwitchTo(ControlModules.Keyboard)
		elseif IsTouchDevice then
			ControlState:SwitchTo(ControlModules.Touch)
		end
	end
end)

UserInputService.GamepadConnected:connect(function(gamepadEnum)
	if not VRService.VREnabled then
		ControlState:SwitchTo(ControlModules.Gamepad)
	end
end)

switchToInputType(UserInputService:GetLastInputType())
UserInputService.LastInputTypeChanged:connect(switchToInputType)

VRService.Changed:connect(function(prop)
	if prop ~= "VREnabled" then
		return
	end

	if VRService.VREnabled then
		ControlState:SwitchTo(ControlModules.VRNavigation)
	end
end)
