-- If in-game, enable ctrl hotkeys for sibling selection & selection clearing

if Mode == 'Tool' then
	AssignHotkey({ 'LeftControl', 'LeftBracket' }, Support.Call(Targeting.SelectSiblings, false, false));
	AssignHotkey({ 'RightControl', 'LeftBracket' }, Support.Call(Targeting.SelectSiblings, false, false));
	AssignHotkey({ 'LeftControl', 'R' }, Support.Call(Selection.Clear, true));
	AssignHotkey({ 'RightControl', 'R' }, Support.Call(Selection.Clear, true));
end;

function GroupSelection(GroupType)
	-- Groups the selected items

	-- Create history record
	local HistoryRecord = {
		Items = Support.CloneTable(Selection.Items),
		CurrentParents = Support.GetListMembers(Selection.Items, 'Parent')
	}

	function HistoryRecord:Unapply()
		SyncAPI:Invoke('SetParent', self.Items, self.CurrentParents)
		SyncAPI:Invoke('Remove', { self.NewParent })
		Selection.Replace(self.Items)
	end

	function HistoryRecord:Apply()
		SyncAPI:Invoke('UndoRemove', { self.NewParent })
		SyncAPI:Invoke('SetParent', self.Items, self.NewParent)
		Selection.Replace({ self.NewParent })
	end

	-- Perform group creation
	HistoryRecord.NewParent = SyncAPI:Invoke('CreateGroup', GroupType,
		GetHighestParent(HistoryRecord.Items),
		HistoryRecord.Items
	)

	-- Register history record
	History.Add(HistoryRecord)

	-- Select new group
	Selection.Replace({ HistoryRecord.NewParent })

end

function UngroupSelection()
	-- Ungroups the selected groups

	-- Create history record
	local HistoryRecord = {
		Selection = Selection.Items
	}

	function HistoryRecord:Unapply()
		SyncAPI:Invoke('UndoRemove', self.Groups)

		-- Reparent children
		for GroupId, Items in ipairs(self.GroupChildren) do
			coroutine.resume(coroutine.create(function ()
				SyncAPI:Invoke('SetParent', Items, self.Groups[GroupId])
			end))
		end

		-- Reselect groups
		Selection.Replace(self.Selection)
	end

	function HistoryRecord:Apply()

		-- Get groups from selection
		self.Groups = {}
		for _, Item in ipairs(self.Selection) do
			if Item:IsA 'Model' or Item:IsA 'Folder' then
				self.Groups[#self.Groups + 1] = Item
			end
		end

		-- Perform ungrouping
		self.GroupParents = Support.GetListMembers(self.Groups, 'Parent')
		self.GroupChildren = SyncAPI:Invoke('Ungroup', self.Groups)

		-- Get unpacked children
		local UnpackedChildren = Support.CloneTable(self.Selection)
		for GroupId, Children in pairs(self.GroupChildren) do
			for _, Child in ipairs(Children) do
				UnpackedChildren[#UnpackedChildren + 1] = Child
			end
		end

		-- Select unpacked items
		Selection.Replace(UnpackedChildren)

	end

	-- Perform action
	HistoryRecord:Apply()

	-- Register history record
	History.Add(HistoryRecord)

end
