// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Code generated by protoc-gen-go_gapic. DO NOT EDIT.

package managedidentities

import (
	"context"
	"fmt"
	"math"
	"net/url"
	"time"

	"cloud.google.com/go/longrunning"
	lroauto "cloud.google.com/go/longrunning/autogen"
	"github.com/golang/protobuf/proto"
	gax "github.com/googleapis/gax-go/v2"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
	"google.golang.org/api/option/internaloption"
	gtransport "google.golang.org/api/transport/grpc"
	managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1"
	longrunningpb "google.golang.org/genproto/googleapis/longrunning"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

var newClientHook clientHook

// CallOptions contains the retry settings for each method of Client.
type CallOptions struct {
	CreateMicrosoftAdDomain []gax.CallOption
	ResetAdminPassword      []gax.CallOption
	ListDomains             []gax.CallOption
	GetDomain               []gax.CallOption
	UpdateDomain            []gax.CallOption
	DeleteDomain            []gax.CallOption
	AttachTrust             []gax.CallOption
	ReconfigureTrust        []gax.CallOption
	DetachTrust             []gax.CallOption
	ValidateTrust           []gax.CallOption
}

func defaultClientOptions() []option.ClientOption {
	return []option.ClientOption{
		internaloption.WithDefaultEndpoint("managedidentities.googleapis.com:443"),
		internaloption.WithDefaultMTLSEndpoint("managedidentities.mtls.googleapis.com:443"),
		internaloption.WithDefaultAudience("https://managedidentities.googleapis.com/"),
		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
		option.WithGRPCDialOption(grpc.WithDisableServiceConfig()),
		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
	}
}

func defaultCallOptions() *CallOptions {
	return &CallOptions{
		CreateMicrosoftAdDomain: []gax.CallOption{},
		ResetAdminPassword:      []gax.CallOption{},
		ListDomains:             []gax.CallOption{},
		GetDomain:               []gax.CallOption{},
		UpdateDomain:            []gax.CallOption{},
		DeleteDomain:            []gax.CallOption{},
		AttachTrust:             []gax.CallOption{},
		ReconfigureTrust:        []gax.CallOption{},
		DetachTrust:             []gax.CallOption{},
		ValidateTrust:           []gax.CallOption{},
	}
}

// Client is a client for interacting with Managed Service for Microsoft Active Directory API.
//
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type Client struct {
	// Connection pool of gRPC connections to the service.
	connPool gtransport.ConnPool

	// flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE
	disableDeadlines bool

	// The gRPC API client.
	client managedidentitiespb.ManagedIdentitiesServiceClient

	// LROClient is used internally to handle longrunning operations.
	// It is exposed so that its CallOptions can be modified if required.
	// Users should not Close this client.
	LROClient *lroauto.OperationsClient

	// The call options for this service.
	CallOptions *CallOptions

	// The x-goog-* metadata to be sent with each request.
	xGoogMetadata metadata.MD
}

// NewClient creates a new managed identities service client.
//
// API Overview
//
// The managedidentites.googleapis.com service implements the Google Cloud
// Managed Identites API for identity services
// (e.g. Microsoft Active Directory).
//
// The Managed Identities service provides methods to manage
// (create/read/update/delete) domains, reset managed identities admin password,
// add/remove domain controllers in GCP regions and add/remove VPC peering.
//
// Data Model
//
// The Managed Identities service exposes the following resources:
//
//   Locations as global, named as follows:
//   projects/{project_id}/locations/global.
//
//   Domains, named as follows:
//   /projects/{project_id}/locations/global/domain/{domain_name}.
//
// The {domain_name} refers to fully qualified domain name in the customer
// project e.g. mydomain.myorganization.com (at http://mydomain.myorganization.com), with the following restrictions:
//
//   Must contain only lowercase letters, numbers, periods and hyphens.
//
//   Must start with a letter.
//
//   Must contain between 2-64 characters.
//
//   Must end with a number or a letter.
//
//   Must not start with period.
//
//   First segement length (mydomain form example above) shouldn’t exceed
//   15 chars.
//
//   The last segment cannot be fully numeric.
//
//   Must be unique within the customer project.
func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
	clientOpts := defaultClientOptions()

	if newClientHook != nil {
		hookOpts, err := newClientHook(ctx, clientHookParams{})
		if err != nil {
			return nil, err
		}
		clientOpts = append(clientOpts, hookOpts...)
	}

	disableDeadlines, err := checkDisableDeadlines()
	if err != nil {
		return nil, err
	}

	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
	if err != nil {
		return nil, err
	}
	c := &Client{
		connPool:         connPool,
		disableDeadlines: disableDeadlines,
		CallOptions:      defaultCallOptions(),

		client: managedidentitiespb.NewManagedIdentitiesServiceClient(connPool),
	}
	c.setGoogleClientInfo()

	c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
	if err != nil {
		// This error "should not happen", since we are just reusing old connection pool
		// and never actually need to dial.
		// If this does happen, we could leak connp. However, we cannot close conn:
		// If the user invoked the constructor with option.WithGRPCConn,
		// we would close a connection that's still in use.
		// TODO: investigate error conditions.
		return nil, err
	}
	return c, nil
}

// Connection returns a connection to the API service.
//
// Deprecated.
func (c *Client) Connection() *grpc.ClientConn {
	return c.connPool.Conn()
}

// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *Client) Close() error {
	return c.connPool.Close()
}

// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *Client) setGoogleClientInfo(keyval ...string) {
	kv := append([]string{"gl-go", versionGo()}, keyval...)
	kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version)
	c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
}

// CreateMicrosoftAdDomain creates a Microsoft AD domain.
func (c *Client) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.CreateMicrosoftAdDomain[0:len(c.CallOptions.CreateMicrosoftAdDomain):len(c.CallOptions.CreateMicrosoftAdDomain)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.CreateMicrosoftAdDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &CreateMicrosoftAdDomainOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, resp),
	}, nil
}

// ResetAdminPassword resets a domain’s administrator password.
func (c *Client) ResetAdminPassword(ctx context.Context, req *managedidentitiespb.ResetAdminPasswordRequest, opts ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.ResetAdminPassword[0:len(c.CallOptions.ResetAdminPassword):len(c.CallOptions.ResetAdminPassword)], opts...)
	var resp *managedidentitiespb.ResetAdminPasswordResponse
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.ResetAdminPassword(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

// ListDomains lists domains in a project.
func (c *Client) ListDomains(ctx context.Context, req *managedidentitiespb.ListDomainsRequest, opts ...gax.CallOption) *DomainIterator {
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.ListDomains[0:len(c.CallOptions.ListDomains):len(c.CallOptions.ListDomains)], opts...)
	it := &DomainIterator{}
	req = proto.Clone(req).(*managedidentitiespb.ListDomainsRequest)
	it.InternalFetch = func(pageSize int, pageToken string) ([]*managedidentitiespb.Domain, string, error) {
		var resp *managedidentitiespb.ListDomainsResponse
		req.PageToken = pageToken
		if pageSize > math.MaxInt32 {
			req.PageSize = math.MaxInt32
		} else {
			req.PageSize = int32(pageSize)
		}
		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
			var err error
			resp, err = c.client.ListDomains(ctx, req, settings.GRPC...)
			return err
		}, opts...)
		if err != nil {
			return nil, "", err
		}

		it.Response = resp
		return resp.GetDomains(), resp.GetNextPageToken(), nil
	}
	fetch := func(pageSize int, pageToken string) (string, error) {
		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
		if err != nil {
			return "", err
		}
		it.items = append(it.items, items...)
		return nextPageToken, nil
	}
	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
	it.pageInfo.MaxSize = int(req.GetPageSize())
	it.pageInfo.Token = req.GetPageToken()
	return it
}

// GetDomain gets information about a domain.
func (c *Client) GetDomain(ctx context.Context, req *managedidentitiespb.GetDomainRequest, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.GetDomain[0:len(c.CallOptions.GetDomain):len(c.CallOptions.GetDomain)], opts...)
	var resp *managedidentitiespb.Domain
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.GetDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

// UpdateDomain updates the metadata and configuration of a domain.
func (c *Client) UpdateDomain(ctx context.Context, req *managedidentitiespb.UpdateDomainRequest, opts ...gax.CallOption) (*UpdateDomainOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "domain.name", url.QueryEscape(req.GetDomain().GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.UpdateDomain[0:len(c.CallOptions.UpdateDomain):len(c.CallOptions.UpdateDomain)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.UpdateDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &UpdateDomainOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, resp),
	}, nil
}

// DeleteDomain deletes a domain.
func (c *Client) DeleteDomain(ctx context.Context, req *managedidentitiespb.DeleteDomainRequest, opts ...gax.CallOption) (*DeleteDomainOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.DeleteDomain[0:len(c.CallOptions.DeleteDomain):len(c.CallOptions.DeleteDomain)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.DeleteDomain(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &DeleteDomainOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, resp),
	}, nil
}

// AttachTrust adds an AD trust to a domain.
func (c *Client) AttachTrust(ctx context.Context, req *managedidentitiespb.AttachTrustRequest, opts ...gax.CallOption) (*AttachTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.AttachTrust[0:len(c.CallOptions.AttachTrust):len(c.CallOptions.AttachTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.AttachTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &AttachTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, resp),
	}, nil
}

// ReconfigureTrust updates the DNS conditional forwarder.
func (c *Client) ReconfigureTrust(ctx context.Context, req *managedidentitiespb.ReconfigureTrustRequest, opts ...gax.CallOption) (*ReconfigureTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.ReconfigureTrust[0:len(c.CallOptions.ReconfigureTrust):len(c.CallOptions.ReconfigureTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.ReconfigureTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &ReconfigureTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, resp),
	}, nil
}

// DetachTrust removes an AD trust.
func (c *Client) DetachTrust(ctx context.Context, req *managedidentitiespb.DetachTrustRequest, opts ...gax.CallOption) (*DetachTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.DetachTrust[0:len(c.CallOptions.DetachTrust):len(c.CallOptions.DetachTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.DetachTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &DetachTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, resp),
	}, nil
}

// ValidateTrust validates a trust state, that the target domain is reachable, and that the
// target domain is able to accept incoming trust requests.
func (c *Client) ValidateTrust(ctx context.Context, req *managedidentitiespb.ValidateTrustRequest, opts ...gax.CallOption) (*ValidateTrustOperation, error) {
	if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
		cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
		defer cancel()
		ctx = cctx
	}
	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
	opts = append(c.CallOptions.ValidateTrust[0:len(c.CallOptions.ValidateTrust):len(c.CallOptions.ValidateTrust)], opts...)
	var resp *longrunningpb.Operation
	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
		var err error
		resp, err = c.client.ValidateTrust(ctx, req, settings.GRPC...)
		return err
	}, opts...)
	if err != nil {
		return nil, err
	}
	return &ValidateTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, resp),
	}, nil
}

// AttachTrustOperation manages a long-running operation from AttachTrust.
type AttachTrustOperation struct {
	lro *longrunning.Operation
}

// AttachTrustOperation returns a new AttachTrustOperation from a given name.
// The name must be that of a previously created AttachTrustOperation, possibly from a different process.
func (c *Client) AttachTrustOperation(name string) *AttachTrustOperation {
	return &AttachTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *AttachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *AttachTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *AttachTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *AttachTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *AttachTrustOperation) Name() string {
	return op.lro.Name()
}

// CreateMicrosoftAdDomainOperation manages a long-running operation from CreateMicrosoftAdDomain.
type CreateMicrosoftAdDomainOperation struct {
	lro *longrunning.Operation
}

// CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name.
// The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process.
func (c *Client) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation {
	return &CreateMicrosoftAdDomainOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *CreateMicrosoftAdDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *CreateMicrosoftAdDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *CreateMicrosoftAdDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *CreateMicrosoftAdDomainOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *CreateMicrosoftAdDomainOperation) Name() string {
	return op.lro.Name()
}

// DeleteDomainOperation manages a long-running operation from DeleteDomain.
type DeleteDomainOperation struct {
	lro *longrunning.Operation
}

// DeleteDomainOperation returns a new DeleteDomainOperation from a given name.
// The name must be that of a previously created DeleteDomainOperation, possibly from a different process.
func (c *Client) DeleteDomainOperation(name string) *DeleteDomainOperation {
	return &DeleteDomainOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *DeleteDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) error {
	return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...)
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *DeleteDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) error {
	return op.lro.Poll(ctx, nil, opts...)
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *DeleteDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *DeleteDomainOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *DeleteDomainOperation) Name() string {
	return op.lro.Name()
}

// DetachTrustOperation manages a long-running operation from DetachTrust.
type DetachTrustOperation struct {
	lro *longrunning.Operation
}

// DetachTrustOperation returns a new DetachTrustOperation from a given name.
// The name must be that of a previously created DetachTrustOperation, possibly from a different process.
func (c *Client) DetachTrustOperation(name string) *DetachTrustOperation {
	return &DetachTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *DetachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *DetachTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *DetachTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *DetachTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *DetachTrustOperation) Name() string {
	return op.lro.Name()
}

// ReconfigureTrustOperation manages a long-running operation from ReconfigureTrust.
type ReconfigureTrustOperation struct {
	lro *longrunning.Operation
}

// ReconfigureTrustOperation returns a new ReconfigureTrustOperation from a given name.
// The name must be that of a previously created ReconfigureTrustOperation, possibly from a different process.
func (c *Client) ReconfigureTrustOperation(name string) *ReconfigureTrustOperation {
	return &ReconfigureTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *ReconfigureTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *ReconfigureTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *ReconfigureTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *ReconfigureTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *ReconfigureTrustOperation) Name() string {
	return op.lro.Name()
}

// UpdateDomainOperation manages a long-running operation from UpdateDomain.
type UpdateDomainOperation struct {
	lro *longrunning.Operation
}

// UpdateDomainOperation returns a new UpdateDomainOperation from a given name.
// The name must be that of a previously created UpdateDomainOperation, possibly from a different process.
func (c *Client) UpdateDomainOperation(name string) *UpdateDomainOperation {
	return &UpdateDomainOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *UpdateDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *UpdateDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *UpdateDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *UpdateDomainOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *UpdateDomainOperation) Name() string {
	return op.lro.Name()
}

// ValidateTrustOperation manages a long-running operation from ValidateTrust.
type ValidateTrustOperation struct {
	lro *longrunning.Operation
}

// ValidateTrustOperation returns a new ValidateTrustOperation from a given name.
// The name must be that of a previously created ValidateTrustOperation, possibly from a different process.
func (c *Client) ValidateTrustOperation(name string) *ValidateTrustOperation {
	return &ValidateTrustOperation{
		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
	}
}

// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *ValidateTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
		return nil, err
	}
	return &resp, nil
}

// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *ValidateTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) {
	var resp managedidentitiespb.Domain
	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
		return nil, err
	}
	if !op.Done() {
		return nil, nil
	}
	return &resp, nil
}

// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *ValidateTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) {
	var meta managedidentitiespb.OpMetadata
	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	return &meta, nil
}

// Done reports whether the long-running operation has completed.
func (op *ValidateTrustOperation) Done() bool {
	return op.lro.Done()
}

// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *ValidateTrustOperation) Name() string {
	return op.lro.Name()
}

// DomainIterator manages a stream of *managedidentitiespb.Domain.
type DomainIterator struct {
	items    []*managedidentitiespb.Domain
	pageInfo *iterator.PageInfo
	nextFunc func() error

	// Response is the raw response for the current page.
	// It must be cast to the RPC response type.
	// Calling Next() or InternalFetch() updates this value.
	Response interface{}

	// InternalFetch is for use by the Google Cloud Libraries only.
	// It is not part of the stable interface of this package.
	//
	// InternalFetch returns results from a single call to the underlying RPC.
	// The number of results is no greater than pageSize.
	// If there are no more results, nextPageToken is empty and err is nil.
	InternalFetch func(pageSize int, pageToken string) (results []*managedidentitiespb.Domain, nextPageToken string, err error)
}

// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *DomainIterator) PageInfo() *iterator.PageInfo {
	return it.pageInfo
}

// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *DomainIterator) Next() (*managedidentitiespb.Domain, error) {
	var item *managedidentitiespb.Domain
	if err := it.nextFunc(); err != nil {
		return item, err
	}
	item = it.items[0]
	it.items = it.items[1:]
	return item, nil
}

func (it *DomainIterator) bufLen() int {
	return len(it.items)
}

func (it *DomainIterator) takeBuf() interface{} {
	b := it.items
	it.items = nil
	return b
}
