/*
 * 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 { WorkflowTriggerHistories } 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 {
  WorkflowTriggerHistory,
  WorkflowTriggerHistoriesListNextOptionalParams,
  WorkflowTriggerHistoriesListOptionalParams,
  WorkflowTriggerHistoriesListResponse,
  WorkflowTriggerHistoriesGetOptionalParams,
  WorkflowTriggerHistoriesGetResponse,
  WorkflowTriggerHistoriesResubmitOptionalParams,
  WorkflowTriggerHistoriesListNextResponse
} from "../models";

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

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

  /**
   * Gets a list of workflow trigger histories.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Site name.
   * @param workflowName The workflow name.
   * @param triggerName The workflow trigger name.
   * @param options The options parameters.
   */
  public list(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    options?: WorkflowTriggerHistoriesListOptionalParams
  ): PagedAsyncIterableIterator<WorkflowTriggerHistory> {
    const iter = this.listPagingAll(
      resourceGroupName,
      name,
      workflowName,
      triggerName,
      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.listPagingPage(
          resourceGroupName,
          name,
          workflowName,
          triggerName,
          options,
          settings
        );
      }
    };
  }

  private async *listPagingPage(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    options?: WorkflowTriggerHistoriesListOptionalParams,
    settings?: PageSettings
  ): AsyncIterableIterator<WorkflowTriggerHistory[]> {
    let result: WorkflowTriggerHistoriesListResponse;
    let continuationToken = settings?.continuationToken;
    if (!continuationToken) {
      result = await this._list(
        resourceGroupName,
        name,
        workflowName,
        triggerName,
        options
      );
      let page = result.value || [];
      continuationToken = result.nextLink;
      setContinuationToken(page, continuationToken);
      yield page;
    }
    while (continuationToken) {
      result = await this._listNext(
        resourceGroupName,
        name,
        workflowName,
        triggerName,
        continuationToken,
        options
      );
      continuationToken = result.nextLink;
      let page = result.value || [];
      setContinuationToken(page, continuationToken);
      yield page;
    }
  }

  private async *listPagingAll(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    options?: WorkflowTriggerHistoriesListOptionalParams
  ): AsyncIterableIterator<WorkflowTriggerHistory> {
    for await (const page of this.listPagingPage(
      resourceGroupName,
      name,
      workflowName,
      triggerName,
      options
    )) {
      yield* page;
    }
  }

  /**
   * Gets a list of workflow trigger histories.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Site name.
   * @param workflowName The workflow name.
   * @param triggerName The workflow trigger name.
   * @param options The options parameters.
   */
  private _list(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    options?: WorkflowTriggerHistoriesListOptionalParams
  ): Promise<WorkflowTriggerHistoriesListResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, name, workflowName, triggerName, options },
      listOperationSpec
    );
  }

  /**
   * Gets a workflow trigger history.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Site name.
   * @param workflowName The workflow name.
   * @param triggerName The workflow trigger name.
   * @param historyName The workflow trigger history name. Corresponds to the run name for triggers that
   *                    resulted in a run.
   * @param options The options parameters.
   */
  get(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    historyName: string,
    options?: WorkflowTriggerHistoriesGetOptionalParams
  ): Promise<WorkflowTriggerHistoriesGetResponse> {
    return this.client.sendOperationRequest(
      {
        resourceGroupName,
        name,
        workflowName,
        triggerName,
        historyName,
        options
      },
      getOperationSpec
    );
  }

  /**
   * Resubmits a workflow run based on the trigger history.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Site name.
   * @param workflowName The workflow name.
   * @param triggerName The workflow trigger name.
   * @param historyName The workflow trigger history name. Corresponds to the run name for triggers that
   *                    resulted in a run.
   * @param options The options parameters.
   */
  async beginResubmit(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    historyName: string,
    options?: WorkflowTriggerHistoriesResubmitOptionalParams
  ): 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,
        workflowName,
        triggerName,
        historyName,
        options
      },
      spec: resubmitOperationSpec
    });
    const poller = await createHttpPoller<void, OperationState<void>>(lro, {
      restoreFrom: options?.resumeFrom,
      intervalInMs: options?.updateIntervalInMs
    });
    await poller.poll();
    return poller;
  }

  /**
   * Resubmits a workflow run based on the trigger history.
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Site name.
   * @param workflowName The workflow name.
   * @param triggerName The workflow trigger name.
   * @param historyName The workflow trigger history name. Corresponds to the run name for triggers that
   *                    resulted in a run.
   * @param options The options parameters.
   */
  async beginResubmitAndWait(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    historyName: string,
    options?: WorkflowTriggerHistoriesResubmitOptionalParams
  ): Promise<void> {
    const poller = await this.beginResubmit(
      resourceGroupName,
      name,
      workflowName,
      triggerName,
      historyName,
      options
    );
    return poller.pollUntilDone();
  }

  /**
   * ListNext
   * @param resourceGroupName Name of the resource group to which the resource belongs.
   * @param name Site name.
   * @param workflowName The workflow name.
   * @param triggerName The workflow trigger name.
   * @param nextLink The nextLink from the previous successful call to the List method.
   * @param options The options parameters.
   */
  private _listNext(
    resourceGroupName: string,
    name: string,
    workflowName: string,
    triggerName: string,
    nextLink: string,
    options?: WorkflowTriggerHistoriesListNextOptionalParams
  ): Promise<WorkflowTriggerHistoriesListNextResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, name, workflowName, triggerName, nextLink, options },
      listNextOperationSpec
    );
  }
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);

const listOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{workflowName}/triggers/{triggerName}/histories",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.WorkflowTriggerHistoryListResult
    },
    default: {
      bodyMapper: Mappers.ErrorResponse
    }
  },
  queryParameters: [Parameters.apiVersion, Parameters.top1, Parameters.filter1],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name,
    Parameters.workflowName1,
    Parameters.triggerName
  ],
  headerParameters: [Parameters.accept],
  serializer
};
const getOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{workflowName}/triggers/{triggerName}/histories/{historyName}",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.WorkflowTriggerHistory
    },
    default: {
      bodyMapper: Mappers.ErrorResponse
    }
  },
  queryParameters: [Parameters.apiVersion],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name,
    Parameters.workflowName1,
    Parameters.triggerName,
    Parameters.historyName
  ],
  headerParameters: [Parameters.accept],
  serializer
};
const resubmitOperationSpec: coreClient.OperationSpec = {
  path:
    "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{workflowName}/triggers/{triggerName}/histories/{historyName}/resubmit",
  httpMethod: "POST",
  responses: {
    200: {},
    201: {},
    202: {},
    204: {},
    default: {
      bodyMapper: Mappers.ErrorResponse
    }
  },
  queryParameters: [Parameters.apiVersion],
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name,
    Parameters.workflowName1,
    Parameters.triggerName,
    Parameters.historyName
  ],
  headerParameters: [Parameters.accept],
  serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
  path: "{nextLink}",
  httpMethod: "GET",
  responses: {
    200: {
      bodyMapper: Mappers.WorkflowTriggerHistoryListResult
    },
    default: {
      bodyMapper: Mappers.ErrorResponse
    }
  },
  urlParameters: [
    Parameters.$host,
    Parameters.subscriptionId,
    Parameters.resourceGroupName,
    Parameters.name,
    Parameters.nextLink,
    Parameters.workflowName1,
    Parameters.triggerName
  ],
  headerParameters: [Parameters.accept],
  serializer
};
