local module = {}

local function dragger(object,callback,root)
	local finger
	object.InputBegan:Connect(function(input)
		if finger then return end
		if root then
			local objects = game.Players.LocalPlayer.PlayerGui:GetGuiObjectsAtPosition(input.Position.X, input.Position.Y)
			if #objects == 0 or objects[1] == nil then return end -- Roblox what the hell?
			while not objects[1]:IsDescendantOf(root) do table.remove(objects,1) end
			if objects[1] ~= object then return end
		end
		if input.UserInputType == Enum.UserInputType.Touch then finger = input end
		if input.UserInputType == Enum.UserInputType.MouseButton1 then finger = true end
		if not finger then return end
		local options = callback(Vector2.new(input.Position.X,input.Position.Y))
		local function drag(input)
			if options.drag then options.drag(Vector2.new(input.Position.X,input.Position.Y)) end
		end
		drag(input)
		local changed
		changed = _G.Input.InputChanged:Connect(function(input)
			if input.UserInputType == Enum.UserInputType.MouseMovement or input == finger then
				drag(input)
			end
		end)
		local ended
		ended = _G.Input.InputEnded:Connect(function(input)
			if input.UserInputType == Enum.UserInputType.MouseButton1 or input == finger then
				drag(input)
				if options.ended then options.ended(Vector2.new(input.Position.X,input.Position.Y)) end
				changed:Disconnect()
				ended:Disconnect()
				finger = nil
			end
		end)
	end)
end


return {dragger = dragger}
