/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */

import { PagedAsyncIterableIterator, PageSettings } from "@azure/core-paging";
import { setContinuationToken } from "../pagingHelper";
import { KubeEnvironments } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { WebSiteManagementClient } from "../webSiteManagementClient";
import {
  SimplePollerLike,
  OperationState,
  createHttpPoller
} from "@azure/core-lro";
import { createLroSpec } from "../lroImpl";
import {
  KubeEnvironment,
  KubeEnvironmentsListBySubscriptionNextOptionalParams,
  KubeEnvironmentsListBySubscriptionOptionalParams,
  KubeEnvironmentsListBySubscriptionResponse,
  KubeEnvironmentsListByResourceGroupNextOptionalParams,
  KubeEnvironmentsListByResourceGroupOptionalParams,
  KubeEnvironmentsListByResourceGroupResponse,
  KubeEnvironmentsGetOptionalParams,
  KubeEnvironmentsGetResponse,
  KubeEnvironmentsCreateOrUpdateOptionalParams,
  KubeEnvironmentsCreateOrUpdateResponse,
  KubeEnvironmentsDeleteOptionalParams,
  KubeEnvironmentPatchResource,
  KubeEnvironmentsUpdateOptionalParams,
  KubeEnvironmentsUpdateResponse,
  KubeEnvironmentsListBySubscriptionNextResponse,
  KubeEnvironmentsListByResourceGroupNextResponse
} from "../models";

/// <reference lib="esnext.asynciterable" />
/** Class containing KubeEnvironments operations. */
export class KubeEnvironmentsImpl implements KubeEnvironments {
  private readonly client: WebSiteManagementClient;

  /**
   * Initialize a new instance of the class KubeEnvironments class.
   * @param client Reference to the service client
   */
  constructor(client: WebSiteManagementClient) {
    this.client = client;
  }

  /**
   * Description for Get all Kubernetes Environments for a subscription.
   * @param options The options parameters.
   */
  public listBySubscription(
    options?: KubeEnvironmentsListBySubscriptionOptionalParams
  ): PagedAsyncIterableIterator<KubeEnvironment> {
    const iter = this.listBySubscriptionPagingAll(options);
    return {
      next() {
        return iter.next();
      },
      [Symbol.asyncIterator]() {
        return this;
      },
      byPage: (settings?: PageSettings) => {
        if (settings?.maxPageSize) {
          throw new Error("maxPageSize is not supported by this operation.");
        }
        return this.listBySubscriptionPagingPage(options, settings);
      }
    };
  }

  private async *listBySubscriptionPagingPage(
    options?: KubeEnvironmentsListBySubscriptionOptionalParams,
    settings?: PageSettings
  ): AsyncIterableIterator<KubeEnvironment[]> {
    let result: KubeEnvironmentsListBySubscriptionResponse;
    let continuationToken = settings?.continuationToken;
    if (!continuationToken) {
      result = await this._listBySubscription(options);
      let page = result.value || [];
      continuationToken = result.nextLink;
      setContinuationToken(page, continuationToken);
      yield page;
    }
    while (continuationToken) {
      result = await this._listBySubscriptionNext(continuationToken, options);
      continuationToken = result.nextLink;
      let page = result.value || [];
      setContinuationToken(page, continuationToken);
      yield page;
    }
  }

  private async *listBySubscriptionPagingAll(
    options?: KubeEnvironmentsListBySubscriptionOptionalParams
  ): AsyncIterableIterator<KubeEnvironment> {
    for await (const page of this.listBySubscriptionPagingPage(options)) {
      yield* page;
    }
  }

  /**
   * Description for Get all the Kubernetes Environments in a resource group.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param options The options parameters.
   */
  public listByResourceGroup(
    resourceGroupName: string,
    options?: KubeEnvironmentsListByResourceGroupOptionalParams
  ): PagedAsyncIterableIterator<KubeEnvironment> {
    const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
    return {
      next() {
        return iter.next();
      },
      [Symbol.asyncIterator]() {
        return this;
      },
      byPage: (settings?: PageSettings) => {
        if (settings?.maxPageSize) {
          throw new Error("maxPageSize is not supported by this operation.");
        }
        return this.listByResourceGroupPagingPage(
          resourceGroupName,
          options,
          settings
        );
      }
    };
  }

  private async *listByResourceGroupPagingPage(
    resourceGroupName: string,
    options?: KubeEnvironmentsListByResourceGroupOptionalParams,
    settings?: PageSettings
  ): AsyncIterableIterator<KubeEnvironment[]> {
    let result: KubeEnvironmentsListByResourceGroupResponse;
    let continuationToken = settings?.continuationToken;
    if (!continuationToken) {
      result = await this._listByResourceGroup(resourceGroupName, options);
      let page = result.value || [];
      continuationToken = result.nextLink;
      setContinuationToken(page, continuationToken);
      yield page;
    }
    while (continuationToken) {
      result = await this._listByResourceGroupNext(
        resourceGroupName,
        continuationToken,
        options
      );
      continuationToken = result.nextLink;
      let page = result.value || [];
      setContinuationToken(page, continuationToken);
      yield page;
    }
  }

  private async *listByResourceGroupPagingAll(
    resourceGroupName: string,
    options?: KubeEnvironmentsListByResourceGroupOptionalParams
  ): AsyncIterableIterator<KubeEnvironment> {
    for await (const page of this.listByResourceGroupPagingPage(
      resourceGroupName,
      options
    )) {
      yield* page;
    }
  }

  /**
   * Description for Get all Kubernetes Environments for a subscription.
   * @param options The options parameters.
   */
  private _listBySubscription(
    options?: KubeEnvironmentsListBySubscriptionOptionalParams
  ): Promise<KubeEnvironmentsListBySubscriptionResponse> {
    return this.client.sendOperationRequest(
      { options },
      listBySubscriptionOperationSpec
    );
  }

  /**
   * Description for Get all the Kubernetes Environments in a resource group.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param options The options parameters.
   */
  private _listByResourceGroup(
    resourceGroupName: string,
    options?: KubeEnvironmentsListByResourceGroupOptionalParams
  ): Promise<KubeEnvironmentsListByResourceGroupResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, options },
      listByResourceGroupOperationSpec
    );
  }

  /**
   * Description for Get the properties of a Kubernetes Environment.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Name of the Kubernetes Environment.
   * @param options The options parameters.
   */
  get(
    resourceGroupName: string,
    name: string,
    options?: KubeEnvironmentsGetOptionalParams
  ): Promise<KubeEnvironmentsGetResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, name, options },
      getOperationSpec
    );
  }

  /**
   * Description for Creates or updates a Kubernetes Environment.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Name of the Kubernetes Environment.
   * @param kubeEnvironmentEnvelope Configuration details of the Kubernetes Environment.
   * @param options The options parameters.
   */
  async beginCreateOrUpdate(
    resourceGroupName: string,
    name: string,
    kubeEnvironmentEnvelope: KubeEnvironment,
    options?: KubeEnvironmentsCreateOrUpdateOptionalParams
  ): Promise<
    SimplePollerLike<
      OperationState<KubeEnvironmentsCreateOrUpdateResponse>,
      KubeEnvironmentsCreateOrUpdateResponse
    >
  > {
    const directSendOperation = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<KubeEnvironmentsCreateOrUpdateResponse> => {
      return this.client.sendOperationRequest(args, spec);
    };
    const sendOperationFn = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ) => {
      let currentRawResponse:
        | coreClient.FullOperationResponse
        | undefined = undefined;
      const providedCallback = args.options?.onResponse;
      const callback: coreClient.RawResponseCallback = (
        rawResponse: coreClient.FullOperationResponse,
        flatResponse: unknown
      ) => {
        currentRawResponse = rawResponse;
        providedCallback?.(rawResponse, flatResponse);
      };
      const updatedArgs = {
        ...args,
        options: {
          ...args.options,
          onResponse: callback
        }
      };
      const flatResponse = await directSendOperation(updatedArgs, spec);
      return {
        flatResponse,
        rawResponse: {
          statusCode: currentRawResponse!.status,
          body: currentRawResponse!.parsedBody,
          headers: currentRawResponse!.headers.toJSON()
        }
      };
    };

    const lro = createLroSpec({
      sendOperationFn,
      args: { resourceGroupName, name, kubeEnvironmentEnvelope, options },
      spec: createOrUpdateOperationSpec
    });
    const poller = await createHttpPoller<
      KubeEnvironmentsCreateOrUpdateResponse,
      OperationState<KubeEnvironmentsCreateOrUpdateResponse>
    >(lro, {
      restoreFrom: options?.resumeFrom,
      intervalInMs: options?.updateIntervalInMs
    });
    await poller.poll();
    return poller;
  }

  /**
   * Description for Creates or updates a Kubernetes Environment.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Name of the Kubernetes Environment.
   * @param kubeEnvironmentEnvelope Configuration details of the Kubernetes Environment.
   * @param options The options parameters.
   */
  async beginCreateOrUpdateAndWait(
    resourceGroupName: string,
    name: string,
    kubeEnvironmentEnvelope: KubeEnvironment,
    options?: KubeEnvironmentsCreateOrUpdateOptionalParams
  ): Promise<KubeEnvironmentsCreateOrUpdateResponse> {
    const poller = await this.beginCreateOrUpdate(
      resourceGroupName,
      name,
      kubeEnvironmentEnvelope,
      options
    );
    return poller.pollUntilDone();
  }

  /**
   * Description for Delete a Kubernetes Environment.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Name of the Kubernetes Environment.
   * @param options The options parameters.
   */
  async beginDelete(
    resourceGroupName: string,
    name: string,
    options?: KubeEnvironmentsDeleteOptionalParams
  ): Promise<SimplePollerLike<OperationState<void>, void>> {
    const directSendOperation = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<void> => {
      return this.client.sendOperationRequest(args, spec);
    };
    const sendOperationFn = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ) => {
      let currentRawResponse:
        | coreClient.FullOperationResponse
        | undefined = undefined;
      const providedCallback = args.options?.onResponse;
      const callback: coreClient.RawResponseCallback = (
        rawResponse: coreClient.FullOperationResponse,
        flatResponse: unknown
      ) => {
        currentRawResponse = rawResponse;
        providedCallback?.(rawResponse, flatResponse);
      };
      const updatedArgs = {
        ...args,
        options: {
          ...args.options,
          onResponse: callback
        }
      };
      const flatResponse = await directSendOperation(updatedArgs, spec);
      return {
        flatResponse,
        rawResponse: {
          statusCode: currentRawResponse!.status,
          body: currentRawResponse!.parsedBody,
          headers: currentRawResponse!.headers.toJSON()
        }
      };
    };

    const lro = createLroSpec({
      sendOperationFn,
      args: { resourceGroupName, name, options },
      spec: deleteOperationSpec
    });
    const poller = await createHttpPoller<void, OperationState<void>>(lro, {
      restoreFrom: options?.resumeFrom,
      intervalInMs: options?.updateIntervalInMs
    });
    await poller.poll();
    return poller;
  }

  /**
   * Description for Delete a Kubernetes Environment.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Name of the Kubernetes Environment.
   * @param options The options parameters.
   */
  async beginDeleteAndWait(
    resourceGroupName: string,
    name: string,
    options?: KubeEnvironmentsDeleteOptionalParams
  ): Promise<void> {
    const poller = await this.beginDelete(resourceGroupName, name, options);
    return poller.pollUntilDone();
  }

  /**
   * Description for Creates or updates a Kubernetes Environment.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Name of the Kubernetes Environment.
   * @param kubeEnvironmentEnvelope Configuration details of the Kubernetes Environment.
   * @param options The options parameters.
   */
  update(
    resourceGroupName: string,
    name: string,
    kubeEnvironmentEnvelope: KubeEnvironmentPatchResource,
    options?: KubeEnvironmentsUpdateOptionalParams
  ): Promise<KubeEnvironmentsUpdateResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, name, kubeEnvironmentEnvelope, options },
      updateOperationSpec
    );
  }

  /**
   * ListBySubscriptionNext
   * @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
   * @param options The options parameters.
   */
  private _listBySubscriptionNext(
    nextLink: string,
    options?: KubeEnvironmentsListBySubscriptionNextOptionalParams
  ): Promise<KubeEnvironmentsListBySubscriptionNextResponse> {
    return this.client.sendOperationRequest(
      { nextLink, options },
      listBySubscriptionNextOperationSpec
    );
  }

  /**
   * ListByResourceGroupNext
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
   * @param options The options parameters.
   */
  private _listByResourceGroupNext(
    resourceGroupName: string,
    nextLink: string,
    options?: KubeEnvironmentsListByResourceGroupNextOptionalParams
  ): Promise<KubeEnvironmentsListByResourceGroupNextResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, nextLink, options },
      listByResourceGroupNextOperationSpec
    );
  }
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);

const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/providers/Microsoft.Web/kubeEnvironments",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.KubeEnvironmentCollection
    },
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  queryParameters: [Parameters.apiVersion],
  urlParameters: [Parameters.$host, Parameters.subscriptionId],
  headerParameters: [Parameters.accept],
  serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/kubeEnvironments",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.KubeEnvironmentCollection
    },
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  queryParameters: [Parameters.apiVersion],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName
  ],
  headerParameters: [Parameters.accept],
  serializer
};
const getOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/kubeEnvironments/{name}",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.KubeEnvironment
    },
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  queryParameters: [Parameters.apiVersion],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name
  ],
  headerParameters: [Parameters.accept],
  serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/kubeEnvironments/{name}",
  httpMethod: "PUT",
  responses: {
    200: {
      bodyMapper: Mappers.KubeEnvironment
    },
    201: {
      bodyMapper: Mappers.KubeEnvironment
    },
    202: {
      bodyMapper: Mappers.KubeEnvironment
    },
    204: {
      bodyMapper: Mappers.KubeEnvironment
    },
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  requestBody: Parameters.kubeEnvironmentEnvelope,
  queryParameters: [Parameters.apiVersion],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name
  ],
  headerParameters: [Parameters.accept, Parameters.contentType],
  mediaType: "json",
  serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/kubeEnvironments/{name}",
  httpMethod: "DELETE",
  responses: {
    200: {},
    201: {},
    202: {},
    204: {},
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  queryParameters: [Parameters.apiVersion],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name
  ],
  headerParameters: [Parameters.accept],
  serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/kubeEnvironments/{name}",
  httpMethod: "PATCH",
  responses: {
    200: {
      bodyMapper: Mappers.KubeEnvironment
    },
    201: {
      bodyMapper: Mappers.KubeEnvironment
    },
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  requestBody: Parameters.kubeEnvironmentEnvelope1,
  queryParameters: [Parameters.apiVersion],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name
  ],
  headerParameters: [Parameters.accept, Parameters.contentType],
  mediaType: "json",
  serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
  path: "{nextLink}",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.KubeEnvironmentCollection
    },
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.nextLink
  ],
  headerParameters: [Parameters.accept],
  serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
  path: "{nextLink}",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.KubeEnvironmentCollection
    },
    default: {
      bodyMapper: Mappers.DefaultErrorResponse
    }
  },
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.nextLink
  ],
  headerParameters: [Parameters.accept],
  serializer
};
