-- Axis names corresponding to each face

local FaceAxisNames = {
	[Enum.NormalId.Top] = 'Y';
	[Enum.NormalId.Bottom] = 'Y';
	[Enum.NormalId.Front] = 'Z';
	[Enum.NormalId.Back] = 'Z';
	[Enum.NormalId.Left] = 'X';
	[Enum.NormalId.Right] = 'X';
};

function ShowHandles()
	-- Creates and automatically attaches handles to the currently focused part

	-- Autofocus handles on latest focused part
	if not Connections.AutofocusHandle then
		Connections.AutofocusHandle = Selection.FocusChanged:connect(ShowHandles);
	end;

	-- If handles already exist, only show them
	if Handles then
		Handles.Adornee = Selection.Focus;
		Handles.Visible = true;
		Handles.Parent = Selection.Focus and Core.UIContainer or nil;
		return;
	end;

	-- Create the handles
	Handles = Create 'Handles' {
		Name = 'BTResizingHandles';
		Color = ResizeTool.Color;
		Parent = Core.UIContainer;
		Adornee = Selection.Focus;
	};

	--------------------------------------------------------
	-- Prepare for resizing parts when the handle is clicked
	--------------------------------------------------------

	local AreaPermissions;

	Handles.MouseButton1Down:connect(function ()

		-- Prevent selection
		Core.Targeting.CancelSelecting();

		-- Indicate resizing via handles
		HandleResizing = true;

		-- Stop parts from moving, and capture the initial state of the parts
		InitialState = PreparePartsForResizing();

		-- Track the change
		TrackChange();

		-- Cache area permissions information
		if Core.Mode == 'Tool' then
			AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Selection.Items), Core.Player);
		end;

	end);

	------------------------------------------
	-- Update parts when the handles are moved
	------------------------------------------

	Handles.MouseDrag:connect(function (Face, Distance)

		-- Only resize if handle is enabled
		if not HandleResizing then
			return;
		end;

		-- Calculate the increment-aligned drag distance
		Distance = GetIncrementMultiple(Distance, ResizeTool.Increment);

		-- Resize the parts on the selected faces by the calculated distance
		local Success, Adjustment = ResizePartsByFace(Face, Distance, ResizeTool.Directions, InitialState);

		-- If the resizing did not succeed, resize according to the suggested adjustment
		if not Success then
			ResizePartsByFace(Face, Adjustment, ResizeTool.Directions, InitialState);
		end;

		-- Update the "studs resized" indicator
		if ResizeTool.UI then
			ResizeTool.UI.Changes.Text.Text = 'resized ' .. Support.Round(math.abs(Adjustment or Distance), 3) .. ' studs';
		end;

		-- Make sure we're not entering any unauthorized private areas
		if Core.Mode == 'Tool' and Security.ArePartsViolatingAreas(Selection.Items, Core.Player, false, AreaPermissions) then
			for Part, State in pairs(InitialState) do
				Part.Size = State.Size;
				Part.CFrame = State.CFrame;
			end;
		end;

	end);

end;

