/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

const msRest = require('ms-rest');
const msRestAzure = require('ms-rest-azure');
const WebResource = msRest.WebResource;

/**
 * Gets an extended database's blob auditing policy.
 *
 * @param {string} resourceGroupName The name of the resource group that
 * contains the resource. You can obtain this value from the Azure Resource
 * Manager API or the portal.
 *
 * @param {string} serverName The name of the server.
 *
 * @param {string} databaseName The name of the database.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link ExtendedDatabaseBlobAuditingPolicy} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _get(resourceGroupName, serverName, databaseName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let blobAuditingPolicyName = 'default';
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (databaseName === null || databaseName === undefined || typeof databaseName.valueOf() !== 'string') {
      throw new Error('databaseName cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/extendedAuditingSettings/{blobAuditingPolicyName}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{databaseName}', encodeURIComponent(databaseName));
  requestUrl = requestUrl.replace('{blobAuditingPolicyName}', encodeURIComponent(blobAuditingPolicyName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['ExtendedDatabaseBlobAuditingPolicy']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Creates or updates an extended database's blob auditing policy.
 *
 * @param {string} resourceGroupName The name of the resource group that
 * contains the resource. You can obtain this value from the Azure Resource
 * Manager API or the portal.
 *
 * @param {string} serverName The name of the server.
 *
 * @param {string} databaseName The name of the database.
 *
 * @param {object} parameters The extended database blob auditing policy.
 *
 * @param {string} [parameters.predicateExpression] Specifies condition of
 * where clause when creating an audit.
 *
 * @param {string} parameters.state Specifies the state of the policy. If state
 * is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required.
 * Possible values include: 'Enabled', 'Disabled'
 *
 * @param {string} [parameters.storageEndpoint] Specifies the blob storage
 * endpoint (e.g. https://MyAccount.blob.core.windows.net). If state is
 * Enabled, storageEndpoint is required.
 *
 * @param {string} [parameters.storageAccountAccessKey] Specifies the
 * identifier key of the auditing storage account. If state is Enabled and
 * storageEndpoint is specified, storageAccountAccessKey is required.
 *
 * @param {number} [parameters.retentionDays] Specifies the number of days to
 * keep in the audit logs in the storage account.
 *
 * @param {array} [parameters.auditActionsAndGroups] Specifies the
 * Actions-Groups and Actions to audit.
 *
 * The recommended set of action groups to use is the following combination -
 * this will audit all the queries and stored procedures executed against the
 * database, as well as successful and failed logins:
 *
 * BATCH_COMPLETED_GROUP,
 * SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP,
 * FAILED_DATABASE_AUTHENTICATION_GROUP.
 *
 * This above combination is also the set that is configured by default when
 * enabling auditing from the Azure portal.
 *
 * The supported action groups to audit are (note: choose only specific groups
 * that cover your auditing needs. Using unnecessary groups could lead to very
 * large quantities of audit records):
 *
 * APPLICATION_ROLE_CHANGE_PASSWORD_GROUP
 * BACKUP_RESTORE_GROUP
 * DATABASE_LOGOUT_GROUP
 * DATABASE_OBJECT_CHANGE_GROUP
 * DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP
 * DATABASE_OBJECT_PERMISSION_CHANGE_GROUP
 * DATABASE_OPERATION_GROUP
 * DATABASE_PERMISSION_CHANGE_GROUP
 * DATABASE_PRINCIPAL_CHANGE_GROUP
 * DATABASE_PRINCIPAL_IMPERSONATION_GROUP
 * DATABASE_ROLE_MEMBER_CHANGE_GROUP
 * FAILED_DATABASE_AUTHENTICATION_GROUP
 * SCHEMA_OBJECT_ACCESS_GROUP
 * SCHEMA_OBJECT_CHANGE_GROUP
 * SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP
 * SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP
 * SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
 * USER_CHANGE_PASSWORD_GROUP
 * BATCH_STARTED_GROUP
 * BATCH_COMPLETED_GROUP
 *
 * These are groups that cover all sql statements and stored procedures
 * executed against the database, and should not be used in combination with
 * other groups as this will result in duplicate audit logs.
 *
 * For more information, see [Database-Level Audit Action
 * Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups).
 *
 * For Database auditing policy, specific Actions can also be specified (note
 * that Actions cannot be specified for Server auditing policy). The supported
 * actions to audit are:
 * SELECT
 * UPDATE
 * INSERT
 * DELETE
 * EXECUTE
 * RECEIVE
 * REFERENCES
 *
 * The general form for defining an action to be audited is:
 * {action} ON {object} BY {principal}
 *
 * Note that <object> in the above format can refer to an object like a table,
 * view, or stored procedure, or an entire database or schema. For the latter
 * cases, the forms DATABASE::{db_name} and SCHEMA::{schema_name} are used,
 * respectively.
 *
 * For example:
 * SELECT on dbo.myTable by public
 * SELECT on DATABASE::myDatabase by public
 * SELECT on SCHEMA::mySchema by public
 *
 * For more information, see [Database-Level Audit
 * Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions)
 *
 * @param {uuid} [parameters.storageAccountSubscriptionId] Specifies the blob
 * storage subscription Id.
 *
 * @param {boolean} [parameters.isStorageSecondaryKeyInUse] Specifies whether
 * storageAccountAccessKey value is the storage's secondary key.
 *
 * @param {boolean} [parameters.isAzureMonitorTargetEnabled] Specifies whether
 * audit events are sent to Azure Monitor.
 * In order to send the events to Azure Monitor, specify 'State' as 'Enabled'
 * and 'IsAzureMonitorTargetEnabled' as true.
 *
 * When using REST API to configure auditing, Diagnostic Settings with
 * 'SQLSecurityAuditEvents' diagnostic logs category on the database should be
 * also created.
 * Note that for server level audit you should use the 'master' database as
 * {databaseName}.
 *
 * Diagnostic Settings URI format:
 * PUT
 * https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview
 *
 * For more information, see [Diagnostic Settings REST
 * API](https://go.microsoft.com/fwlink/?linkid=2033207)
 * or [Diagnostic Settings
 * PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043)
 *
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link ExtendedDatabaseBlobAuditingPolicy} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _createOrUpdate(resourceGroupName, serverName, databaseName, parameters, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let blobAuditingPolicyName = 'default';
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (databaseName === null || databaseName === undefined || typeof databaseName.valueOf() !== 'string') {
      throw new Error('databaseName cannot be null or undefined and it must be of type string.');
    }
    if (parameters === null || parameters === undefined) {
      throw new Error('parameters cannot be null or undefined.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/extendedAuditingSettings/{blobAuditingPolicyName}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{databaseName}', encodeURIComponent(databaseName));
  requestUrl = requestUrl.replace('{blobAuditingPolicyName}', encodeURIComponent(blobAuditingPolicyName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  // Serialize Request
  let requestContent = null;
  let requestModel = null;
  try {
    if (parameters !== null && parameters !== undefined) {
      let requestModelMapper = new client.models['ExtendedDatabaseBlobAuditingPolicy']().mapper();
      requestModel = client.serialize(requestModelMapper, parameters, 'parameters');
      requestContent = JSON.stringify(requestModel);
    }
  } catch (error) {
    let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
        `payload - ${JSON.stringify(parameters, null, 2)}.`);
    return callback(serializationError);
  }
  httpRequest.body = requestContent;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200 && statusCode !== 201) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['ExtendedDatabaseBlobAuditingPolicy']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }
    // Deserialize Response
    if (statusCode === 201) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['ExtendedDatabaseBlobAuditingPolicy']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError1 = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError1.request = msRest.stripRequest(httpRequest);
        deserializationError1.response = msRest.stripResponse(response);
        return callback(deserializationError1);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/** Class representing a ExtendedDatabaseBlobAuditingPolicies. */
class ExtendedDatabaseBlobAuditingPolicies {
  /**
   * Create a ExtendedDatabaseBlobAuditingPolicies.
   * @param {SqlManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._get = _get;
    this._createOrUpdate = _createOrUpdate;
  }

  /**
   * Gets an extended database's blob auditing policy.
   *
   * @param {string} resourceGroupName The name of the resource group that
   * contains the resource. You can obtain this value from the Azure Resource
   * Manager API or the portal.
   *
   * @param {string} serverName The name of the server.
   *
   * @param {string} databaseName The name of the database.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<ExtendedDatabaseBlobAuditingPolicy>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, serverName, databaseName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, serverName, databaseName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets an extended database's blob auditing policy.
   *
   * @param {string} resourceGroupName The name of the resource group that
   * contains the resource. You can obtain this value from the Azure Resource
   * Manager API or the portal.
   *
   * @param {string} serverName The name of the server.
   *
   * @param {string} databaseName The name of the database.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {ExtendedDatabaseBlobAuditingPolicy} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link ExtendedDatabaseBlobAuditingPolicy} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  get(resourceGroupName, serverName, databaseName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._get(resourceGroupName, serverName, databaseName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, serverName, databaseName, options, optionalCallback);
    }
  }

  /**
   * Creates or updates an extended database's blob auditing policy.
   *
   * @param {string} resourceGroupName The name of the resource group that
   * contains the resource. You can obtain this value from the Azure Resource
   * Manager API or the portal.
   *
   * @param {string} serverName The name of the server.
   *
   * @param {string} databaseName The name of the database.
   *
   * @param {object} parameters The extended database blob auditing policy.
   *
   * @param {string} [parameters.predicateExpression] Specifies condition of
   * where clause when creating an audit.
   *
   * @param {string} parameters.state Specifies the state of the policy. If state
   * is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required.
   * Possible values include: 'Enabled', 'Disabled'
   *
   * @param {string} [parameters.storageEndpoint] Specifies the blob storage
   * endpoint (e.g. https://MyAccount.blob.core.windows.net). If state is
   * Enabled, storageEndpoint is required.
   *
   * @param {string} [parameters.storageAccountAccessKey] Specifies the
   * identifier key of the auditing storage account. If state is Enabled and
   * storageEndpoint is specified, storageAccountAccessKey is required.
   *
   * @param {number} [parameters.retentionDays] Specifies the number of days to
   * keep in the audit logs in the storage account.
   *
   * @param {array} [parameters.auditActionsAndGroups] Specifies the
   * Actions-Groups and Actions to audit.
   *
   * The recommended set of action groups to use is the following combination -
   * this will audit all the queries and stored procedures executed against the
   * database, as well as successful and failed logins:
   *
   * BATCH_COMPLETED_GROUP,
   * SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP,
   * FAILED_DATABASE_AUTHENTICATION_GROUP.
   *
   * This above combination is also the set that is configured by default when
   * enabling auditing from the Azure portal.
   *
   * The supported action groups to audit are (note: choose only specific groups
   * that cover your auditing needs. Using unnecessary groups could lead to very
   * large quantities of audit records):
   *
   * APPLICATION_ROLE_CHANGE_PASSWORD_GROUP
   * BACKUP_RESTORE_GROUP
   * DATABASE_LOGOUT_GROUP
   * DATABASE_OBJECT_CHANGE_GROUP
   * DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP
   * DATABASE_OBJECT_PERMISSION_CHANGE_GROUP
   * DATABASE_OPERATION_GROUP
   * DATABASE_PERMISSION_CHANGE_GROUP
   * DATABASE_PRINCIPAL_CHANGE_GROUP
   * DATABASE_PRINCIPAL_IMPERSONATION_GROUP
   * DATABASE_ROLE_MEMBER_CHANGE_GROUP
   * FAILED_DATABASE_AUTHENTICATION_GROUP
   * SCHEMA_OBJECT_ACCESS_GROUP
   * SCHEMA_OBJECT_CHANGE_GROUP
   * SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP
   * SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP
   * SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
   * USER_CHANGE_PASSWORD_GROUP
   * BATCH_STARTED_GROUP
   * BATCH_COMPLETED_GROUP
   *
   * These are groups that cover all sql statements and stored procedures
   * executed against the database, and should not be used in combination with
   * other groups as this will result in duplicate audit logs.
   *
   * For more information, see [Database-Level Audit Action
   * Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups).
   *
   * For Database auditing policy, specific Actions can also be specified (note
   * that Actions cannot be specified for Server auditing policy). The supported
   * actions to audit are:
   * SELECT
   * UPDATE
   * INSERT
   * DELETE
   * EXECUTE
   * RECEIVE
   * REFERENCES
   *
   * The general form for defining an action to be audited is:
   * {action} ON {object} BY {principal}
   *
   * Note that <object> in the above format can refer to an object like a table,
   * view, or stored procedure, or an entire database or schema. For the latter
   * cases, the forms DATABASE::{db_name} and SCHEMA::{schema_name} are used,
   * respectively.
   *
   * For example:
   * SELECT on dbo.myTable by public
   * SELECT on DATABASE::myDatabase by public
   * SELECT on SCHEMA::mySchema by public
   *
   * For more information, see [Database-Level Audit
   * Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions)
   *
   * @param {uuid} [parameters.storageAccountSubscriptionId] Specifies the blob
   * storage subscription Id.
   *
   * @param {boolean} [parameters.isStorageSecondaryKeyInUse] Specifies whether
   * storageAccountAccessKey value is the storage's secondary key.
   *
   * @param {boolean} [parameters.isAzureMonitorTargetEnabled] Specifies whether
   * audit events are sent to Azure Monitor.
   * In order to send the events to Azure Monitor, specify 'State' as 'Enabled'
   * and 'IsAzureMonitorTargetEnabled' as true.
   *
   * When using REST API to configure auditing, Diagnostic Settings with
   * 'SQLSecurityAuditEvents' diagnostic logs category on the database should be
   * also created.
   * Note that for server level audit you should use the 'master' database as
   * {databaseName}.
   *
   * Diagnostic Settings URI format:
   * PUT
   * https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview
   *
   * For more information, see [Diagnostic Settings REST
   * API](https://go.microsoft.com/fwlink/?linkid=2033207)
   * or [Diagnostic Settings
   * PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043)
   *
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<ExtendedDatabaseBlobAuditingPolicy>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  createOrUpdateWithHttpOperationResponse(resourceGroupName, serverName, databaseName, parameters, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._createOrUpdate(resourceGroupName, serverName, databaseName, parameters, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Creates or updates an extended database's blob auditing policy.
   *
   * @param {string} resourceGroupName The name of the resource group that
   * contains the resource. You can obtain this value from the Azure Resource
   * Manager API or the portal.
   *
   * @param {string} serverName The name of the server.
   *
   * @param {string} databaseName The name of the database.
   *
   * @param {object} parameters The extended database blob auditing policy.
   *
   * @param {string} [parameters.predicateExpression] Specifies condition of
   * where clause when creating an audit.
   *
   * @param {string} parameters.state Specifies the state of the policy. If state
   * is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required.
   * Possible values include: 'Enabled', 'Disabled'
   *
   * @param {string} [parameters.storageEndpoint] Specifies the blob storage
   * endpoint (e.g. https://MyAccount.blob.core.windows.net). If state is
   * Enabled, storageEndpoint is required.
   *
   * @param {string} [parameters.storageAccountAccessKey] Specifies the
   * identifier key of the auditing storage account. If state is Enabled and
   * storageEndpoint is specified, storageAccountAccessKey is required.
   *
   * @param {number} [parameters.retentionDays] Specifies the number of days to
   * keep in the audit logs in the storage account.
   *
   * @param {array} [parameters.auditActionsAndGroups] Specifies the
   * Actions-Groups and Actions to audit.
   *
   * The recommended set of action groups to use is the following combination -
   * this will audit all the queries and stored procedures executed against the
   * database, as well as successful and failed logins:
   *
   * BATCH_COMPLETED_GROUP,
   * SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP,
   * FAILED_DATABASE_AUTHENTICATION_GROUP.
   *
   * This above combination is also the set that is configured by default when
   * enabling auditing from the Azure portal.
   *
   * The supported action groups to audit are (note: choose only specific groups
   * that cover your auditing needs. Using unnecessary groups could lead to very
   * large quantities of audit records):
   *
   * APPLICATION_ROLE_CHANGE_PASSWORD_GROUP
   * BACKUP_RESTORE_GROUP
   * DATABASE_LOGOUT_GROUP
   * DATABASE_OBJECT_CHANGE_GROUP
   * DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP
   * DATABASE_OBJECT_PERMISSION_CHANGE_GROUP
   * DATABASE_OPERATION_GROUP
   * DATABASE_PERMISSION_CHANGE_GROUP
   * DATABASE_PRINCIPAL_CHANGE_GROUP
   * DATABASE_PRINCIPAL_IMPERSONATION_GROUP
   * DATABASE_ROLE_MEMBER_CHANGE_GROUP
   * FAILED_DATABASE_AUTHENTICATION_GROUP
   * SCHEMA_OBJECT_ACCESS_GROUP
   * SCHEMA_OBJECT_CHANGE_GROUP
   * SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP
   * SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP
   * SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
   * USER_CHANGE_PASSWORD_GROUP
   * BATCH_STARTED_GROUP
   * BATCH_COMPLETED_GROUP
   *
   * These are groups that cover all sql statements and stored procedures
   * executed against the database, and should not be used in combination with
   * other groups as this will result in duplicate audit logs.
   *
   * For more information, see [Database-Level Audit Action
   * Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups).
   *
   * For Database auditing policy, specific Actions can also be specified (note
   * that Actions cannot be specified for Server auditing policy). The supported
   * actions to audit are:
   * SELECT
   * UPDATE
   * INSERT
   * DELETE
   * EXECUTE
   * RECEIVE
   * REFERENCES
   *
   * The general form for defining an action to be audited is:
   * {action} ON {object} BY {principal}
   *
   * Note that <object> in the above format can refer to an object like a table,
   * view, or stored procedure, or an entire database or schema. For the latter
   * cases, the forms DATABASE::{db_name} and SCHEMA::{schema_name} are used,
   * respectively.
   *
   * For example:
   * SELECT on dbo.myTable by public
   * SELECT on DATABASE::myDatabase by public
   * SELECT on SCHEMA::mySchema by public
   *
   * For more information, see [Database-Level Audit
   * Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions)
   *
   * @param {uuid} [parameters.storageAccountSubscriptionId] Specifies the blob
   * storage subscription Id.
   *
   * @param {boolean} [parameters.isStorageSecondaryKeyInUse] Specifies whether
   * storageAccountAccessKey value is the storage's secondary key.
   *
   * @param {boolean} [parameters.isAzureMonitorTargetEnabled] Specifies whether
   * audit events are sent to Azure Monitor.
   * In order to send the events to Azure Monitor, specify 'State' as 'Enabled'
   * and 'IsAzureMonitorTargetEnabled' as true.
   *
   * When using REST API to configure auditing, Diagnostic Settings with
   * 'SQLSecurityAuditEvents' diagnostic logs category on the database should be
   * also created.
   * Note that for server level audit you should use the 'master' database as
   * {databaseName}.
   *
   * Diagnostic Settings URI format:
   * PUT
   * https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview
   *
   * For more information, see [Diagnostic Settings REST
   * API](https://go.microsoft.com/fwlink/?linkid=2033207)
   * or [Diagnostic Settings
   * PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043)
   *
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {ExtendedDatabaseBlobAuditingPolicy} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link ExtendedDatabaseBlobAuditingPolicy} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  createOrUpdate(resourceGroupName, serverName, databaseName, parameters, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._createOrUpdate(resourceGroupName, serverName, databaseName, parameters, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._createOrUpdate(resourceGroupName, serverName, databaseName, parameters, options, optionalCallback);
    }
  }

}

module.exports = ExtendedDatabaseBlobAuditingPolicies;
