-- Container for temporary connections (disconnected automatically)
local Connections = {};

function TextureTool:Equip()
	-- Enables the tool's equipped functionality

	-- Start up our interface
	self:ShowUI()
	self:EnableSurfaceClickSelection()

	-- Set our current texture type and face
	self:SetTextureType(self.Type)
	self:SetFace(self.Face)

end;

function TextureTool:Unequip()
	-- Disables the tool's equipped functionality

	-- Clear unnecessary resources
	self:HideUI()
	ClearConnections();

end;

function ClearConnections()
	-- Clears out temporary connections

	for ConnectionKey, Connection in pairs(Connections) do
		Connection:Disconnect();
		Connections[ConnectionKey] = nil;
	end;

end;

function TextureTool:ShowUI()
	-- Creates and reveals the UI

	-- Reveal UI if already created
	if self.UI then

		-- Reveal the UI
		self.UI.Visible = true

		-- Update the UI every 0.1 seconds
		self.StopUpdatingUI = Support.Loop(0.1, function ()
			self:UpdateUI()
		end)

		-- Skip UI creation
		return;

	end;

	-- Create the UI
	self.UI = Core.Tool.Interfaces.BTTextureToolGUI:Clone()
	self.UI.Parent = Core.UI
	self.UI.Visible = true

	-- References to UI elements
	local AddButton = self.UI.AddButton
	local RemoveButton = self.UI.RemoveButton
	local DecalModeButton = self.UI.ModeOption.Decal.Button
	local TextureModeButton = self.UI.ModeOption.Texture.Button
	local ImageIdInput = self.UI.ImageIDOption.TextBox
	local TransparencyInput = self.UI.TransparencyOption.Input.TextBox
	local RepeatXInput = self.UI.RepeatOption.XInput.TextBox
	local RepeatYInput = self.UI.RepeatOption.YInput.TextBox

	-- Enable the texture type switch
	DecalModeButton.MouseButton1Click:Connect(function ()
		self:SetTextureType('Decal')
	end);
	TextureModeButton.MouseButton1Click:Connect(function ()
		self:SetTextureType('Texture')
	end);

	-- Create the face selection dropdown
	local Faces = {
		'Top';
		'Bottom';
		'Front';
		'Back';
		'Left';
		'Right'
	};
	local function BuildFaceDropdown()
		return Roact.createElement(Dropdown, {
			Position = UDim2.new(0, 30, 0, 0);
			Size = UDim2.new(1, -45, 0, 25);
			Options = Faces;
			MaxRows = 6;
			CurrentOption = self.Face and self.Face.Name;
			OnOptionSelected = function (Option)
				self:SetFace(Enum.NormalId[Option])
			end;
		})
	end

	-- Mount type dropdown
	local FaceDropdownHandle = Roact.mount(BuildFaceDropdown(), self.UI.SideOption, 'Dropdown')
	self.OnFaceChanged:Connect(function ()
		Roact.update(FaceDropdownHandle, BuildFaceDropdown())
	end)

	-- Enable the image ID input
	ImageIdInput.FocusLost:Connect(function (EnterPressed)
		SetTextureId(TextureTool.Type, TextureTool.Face, ParseAssetId(ImageIdInput.Text));
	end);

	-- Enable other inputs
	SyncInputToProperty('Transparency', TransparencyInput);
	SyncInputToProperty('StudsPerTileU', RepeatXInput);
	SyncInputToProperty('StudsPerTileV', RepeatYInput);

	-- Enable the texture adding button
	AddButton.Button.MouseButton1Click:Connect(function ()
		AddTextures(TextureTool.Type, TextureTool.Face);
	end);
	RemoveButton.Button.MouseButton1Click:Connect(function ()
		RemoveTextures(TextureTool.Type, TextureTool.Face);
	end);

	-- Hook up manual triggering
	local SignatureButton = self.UI:WaitForChild('Title'):WaitForChild('Signature')
	ListenForManualWindowTrigger(TextureTool.ManualText, TextureTool.Color.Color, SignatureButton)

	-- Update the UI every 0.1 seconds
	self.StopUpdatingUI = Support.Loop(0.1, function ()
		self:UpdateUI()
	end)

end;

function SyncInputToProperty(Property, Input)
	-- Enables `Input` to change the given property

	-- Enable inputs
	Input.FocusLost:Connect(function ()
		SetProperty(TextureTool.Type, TextureTool.Face, Property, tonumber(Input.Text));
	end);

end;

function TextureTool:EnableSurfaceClickSelection()
	-- Allows for the setting of the current face by clicking

	-- Clear out any existing connection
	if Connections.SurfaceClickSelection then
		Connections.SurfaceClickSelection:Disconnect();
		Connections.SurfaceClickSelection = nil;
	end;

	-- Add the new click connection
	Connections.SurfaceClickSelection = Core.Mouse.Button1Down:Connect(function ()
		local _, ScopeTarget = Core.Targeting:UpdateTarget()
		if Selection.IsSelected(ScopeTarget) then
			self:SetFace(Core.Mouse.TargetSurface)
		end
	end)

end;

function TextureTool:HideUI()
	-- Hides the tool UI

	-- Make sure there's a UI
	if not self.UI then
		return;
	end;

	-- Hide the UI
	self.UI.Visible = false

	-- Stop updating the UI
	self.StopUpdatingUI()

end;

function GetTextures(TextureType, Face)
	-- Returns all the textures in the selection

	local Textures = {};

	-- Get any textures from any selected parts
	for _, Part in pairs(Selection.Parts) do
		for _, Child in pairs(Part:GetChildren()) do

			-- If this child is texture we're looking for, collect it
			if Child.ClassName == TextureType and Child.Face == Face then
				table.insert(Textures, Child);
			end;

		end;
	end;

	-- Return the found textures
	return Textures;

end;