-- Remove with FFlagPlayerScriptsBindAtPriority

function MouseLockController:OnInputBegan(input, processed)
	if processed then return end
	
	if input.UserInputType == Enum.UserInputType.Keyboard then
		for _, keyCode in pairs(self.boundKeys) do
			if keyCode == input.KeyCode then
				self:OnMouseLockToggled()
				return
			end
		end
	end
end

function MouseLockController:DoMouseLockSwitch(name, state, input)
	if state == Enum.UserInputState.Begin then 
		self:OnMouseLockToggled()
		return Enum.ContextActionResult.Sink
	end
	return Enum.ContextActionResult.Pass
end

function MouseLockController:BindContextActions()
	ContextActionService:BindActionAtPriority(CONTEXT_ACTION_NAME, function(name, state, input) self:DoMouseLockSwitch(name, state, input) end, 
		false, MOUSELOCK_ACTION_PRIORITY, unpack(self.boundKeys))
end

function MouseLockController:UnbindContextActions()
		ContextActionService:UnbindAction(CONTEXT_ACTION_NAME)
end

function MouseLockController:IsMouseLocked()
	return self.enabled and self.isMouseLocked
end

function MouseLockController:EnableMouseLock(enable)
	if enable~=self.enabled then
		
		self.enabled = enable

		if self.enabled then
			-- Enabling the mode
			if FFlagPlayerScriptsBindAtPriority then
				self:BindContextActions()
			else
				if self.inputBeganConn then
					self.inputBeganConn:Disconnect()
				end
				self.inputBeganConn = UserInputService.InputBegan:Connect(function(input, processed)
					self:OnInputBegan(input, processed)
				end)
			end
		else
			-- Disabling
			-- Restore mouse cursor
			if Mouse.Icon~="" then
				Mouse.Icon = ""
			end
			
			if FFlagPlayerScriptsBindAtPriority then
				self:UnbindContextActions()
			else
				if self.inputBeganConn then
					self.inputBeganConn:Disconnect()
				end
				self.inputBeganConn = nil
			end

			-- If the mode is disabled while being used, fire the event to toggle it off
			if self.isMouseLocked then
				self.mouseLockToggledEvent:Fire()
			end			
			
			self.isMouseLocked = false
		end		
		
	end
end

return MouseLockController
