# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.

module Azure::CognitiveServices::FormRecognizer::V1_0_preview
  #
  # A service client - single point of access to the REST API.
  #
  class FormRecognizerClient < MsRestAzure::AzureServiceClient
    include MsRestAzure
    include MsRestAzure::Serialization

    # @return [String] the base URI of the service.
    attr_reader :base_url

    # @return Credentials needed for the client to connect to Azure.
    attr_reader :credentials1

    # @return [String] Supported Cognitive Services endpoints (protocol and
    # hostname, for example: https://westus2.api.cognitive.microsoft.com).
    attr_accessor :endpoint

    # @return Subscription credentials which uniquely identify client
    # subscription.
    attr_accessor :credentials

    # @return [String] The preferred language for the response.
    attr_accessor :accept_language

    # @return [Integer] The retry timeout in seconds for Long Running
    # Operations. Default value is 30.
    attr_accessor :long_running_operation_retry_timeout

    # @return [Boolean] Whether a unique x-ms-client-request-id should be
    # generated. When set to true a unique x-ms-client-request-id value is
    # generated and included in each request. Default is true.
    attr_accessor :generate_client_request_id

    #
    # Creates initializes a new instance of the FormRecognizerClient class.
    # @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client.
    # @param options [Array] filters to be applied to the HTTP requests.
    #
    def initialize(credentials = nil, options = nil)
      super(credentials, options)
      @base_url = '{Endpoint}/formrecognizer/v1.0-preview'

      fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil?
      @credentials = credentials

      @accept_language = 'en-US'
      @long_running_operation_retry_timeout = 30
      @generate_client_request_id = true
      add_telemetry
    end

    #
    # Makes a request and returns the body of the response.
    # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
    # @param path [String] the path, relative to {base_url}.
    # @param options [Hash{String=>String}] specifying any request options like :body.
    # @return [Hash{String=>String}] containing the body of the response.
    # Example:
    #
    #  request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}"
    #  path = "/path"
    #  options = {
    #    body: request_content,
    #    query_params: {'api-version' => '2016-02-01'}
    #  }
    #  result = @client.make_request(:put, path, options)
    #
    def make_request(method, path, options = {})
      result = make_request_with_http_info(method, path, options)
      result.body unless result.nil?
    end

    #
    # Makes a request and returns the operation response.
    # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
    # @param path [String] the path, relative to {base_url}.
    # @param options [Hash{String=>String}] specifying any request options like :body.
    # @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status.
    #
    def make_request_with_http_info(method, path, options = {})
      result = make_request_async(method, path, options).value!
      result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body)
      result
    end

    #
    # Makes a request asynchronously.
    # @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
    # @param path [String] the path, relative to {base_url}.
    # @param options [Hash{String=>String}] specifying any request options like :body.
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def make_request_async(method, path, options = {})
      fail ArgumentError, 'method is nil' if method.nil?
      fail ArgumentError, 'path is nil' if path.nil?

      request_url = options[:base_url] || @base_url
      if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?)
        @request_headers['Content-Type'] = options[:headers]['Content-Type']
      end

      request_headers = @request_headers
      request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil?
      options.merge!({headers: request_headers.merge(options[:headers] || {})})
      options.merge!({credentials: @credentials}) unless @credentials.nil?

      super(request_url, method, path, options)
    end

    #
    # Train Model
    #
    # Create and train a custom model. The train request must include a source
    # parameter that is either an externally accessible Azure Storage blob
    # container Uri (preferably a Shared Access Signature Uri) or valid path to a
    # data folder in a locally mounted drive. When local paths are specified, they
    # must follow the Linux/Unix path format and be an absolute path rooted to the
    # input mount configuration
    # setting value e.g., if '{Mounts:Input}' configuration setting value is
    # '/input' then a valid source path would be '/input/contosodataset'. All data
    # to be trained is expected to be directly under the source folder. Subfolders
    # are not supported. Models are trained using documents that are of the
    # following content type - 'application/pdf', 'image/jpeg' and 'image/png'."
    # Other type of content is ignored.
    #
    # @param train_request [TrainRequest] Request object for training.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [TrainResult] operation results.
    #
    def train_custom_model(train_request, custom_headers:nil)
      response = train_custom_model_async(train_request, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Train Model
    #
    # Create and train a custom model. The train request must include a source
    # parameter that is either an externally accessible Azure Storage blob
    # container Uri (preferably a Shared Access Signature Uri) or valid path to a
    # data folder in a locally mounted drive. When local paths are specified, they
    # must follow the Linux/Unix path format and be an absolute path rooted to the
    # input mount configuration
    # setting value e.g., if '{Mounts:Input}' configuration setting value is
    # '/input' then a valid source path would be '/input/contosodataset'. All data
    # to be trained is expected to be directly under the source folder. Subfolders
    # are not supported. Models are trained using documents that are of the
    # following content type - 'application/pdf', 'image/jpeg' and 'image/png'."
    # Other type of content is ignored.
    #
    # @param train_request [TrainRequest] Request object for training.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def train_custom_model_with_http_info(train_request, custom_headers:nil)
      train_custom_model_async(train_request, custom_headers:custom_headers).value!
    end

    #
    # Train Model
    #
    # Create and train a custom model. The train request must include a source
    # parameter that is either an externally accessible Azure Storage blob
    # container Uri (preferably a Shared Access Signature Uri) or valid path to a
    # data folder in a locally mounted drive. When local paths are specified, they
    # must follow the Linux/Unix path format and be an absolute path rooted to the
    # input mount configuration
    # setting value e.g., if '{Mounts:Input}' configuration setting value is
    # '/input' then a valid source path would be '/input/contosodataset'. All data
    # to be trained is expected to be directly under the source folder. Subfolders
    # are not supported. Models are trained using documents that are of the
    # following content type - 'application/pdf', 'image/jpeg' and 'image/png'."
    # Other type of content is ignored.
    #
    # @param train_request [TrainRequest] Request object for training.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def train_custom_model_async(train_request, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'train_request is nil' if train_request.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?

      # Serialize Request
      request_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::TrainRequest.mapper()
      request_content = self.serialize(request_mapper,  train_request)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'custom/train'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::TrainResult.mapper()
            result.body = self.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Get Keys
    #
    # Retrieve the keys that were
    # extracted during the training of the specified model.
    #
    # @param id Model identifier.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [KeysResult] operation results.
    #
    def get_extracted_keys(id, custom_headers:nil)
      response = get_extracted_keys_async(id, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Get Keys
    #
    # Retrieve the keys that were
    # extracted during the training of the specified model.
    #
    # @param id Model identifier.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def get_extracted_keys_with_http_info(id, custom_headers:nil)
      get_extracted_keys_async(id, custom_headers:custom_headers).value!
    end

    #
    # Get Keys
    #
    # Retrieve the keys that were
    # extracted during the training of the specified model.
    #
    # @param id Model identifier.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def get_extracted_keys_async(id, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'id is nil' if id.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?
      path_template = 'custom/models/{id}/keys'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'id' => id},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::KeysResult.mapper()
            result.body = self.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Get Models
    #
    # Get information about all trained custom models
    #
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [ModelsResult] operation results.
    #
    def get_custom_models(custom_headers:nil)
      response = get_custom_models_async(custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Get Models
    #
    # Get information about all trained custom models
    #
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def get_custom_models_with_http_info(custom_headers:nil)
      get_custom_models_async(custom_headers:custom_headers).value!
    end

    #
    # Get Models
    #
    # Get information about all trained custom models
    #
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def get_custom_models_async(custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?
      path_template = 'custom/models'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::ModelsResult.mapper()
            result.body = self.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Get Model
    #
    # Get information about a model.
    #
    # @param id Model identifier.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [ModelResult] operation results.
    #
    def get_custom_model(id, custom_headers:nil)
      response = get_custom_model_async(id, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Get Model
    #
    # Get information about a model.
    #
    # @param id Model identifier.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def get_custom_model_with_http_info(id, custom_headers:nil)
      get_custom_model_async(id, custom_headers:custom_headers).value!
    end

    #
    # Get Model
    #
    # Get information about a model.
    #
    # @param id Model identifier.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def get_custom_model_async(id, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'id is nil' if id.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?
      path_template = 'custom/models/{id}'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'id' => id},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::ModelResult.mapper()
            result.body = self.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Delete Model
    #
    # Delete model artifacts.
    #
    # @param id The identifier of the model to delete.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    #
    def delete_custom_model(id, custom_headers:nil)
      response = delete_custom_model_async(id, custom_headers:custom_headers).value!
      nil
    end

    #
    # Delete Model
    #
    # Delete model artifacts.
    #
    # @param id The identifier of the model to delete.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def delete_custom_model_with_http_info(id, custom_headers:nil)
      delete_custom_model_async(id, custom_headers:custom_headers).value!
    end

    #
    # Delete Model
    #
    # Delete model artifacts.
    #
    # @param id The identifier of the model to delete.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def delete_custom_model_async(id, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'id is nil' if id.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?
      path_template = 'custom/models/{id}'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'id' => id},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:delete, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 204
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?

        result
      end

      promise.execute
    end

    #
    # Analyze Form
    #
    # Extract key-value pairs from a given document. The input document must be of
    # one of the supported content types - 'application/pdf', 'image/jpeg' or
    # 'image/png'. A success response is returned in JSON.
    #
    # @param id Model Identifier to analyze the document with.
    # @param form_stream A pdf document or image (jpg,png) file to analyze.
    # @param keys [Array<String>] An optional list of known keys to extract the
    # values for.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [AnalyzeResult] operation results.
    #
    def analyze_with_custom_model(id, form_stream, keys:nil, custom_headers:nil)
      response = analyze_with_custom_model_async(id, form_stream, keys:keys, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # Analyze Form
    #
    # Extract key-value pairs from a given document. The input document must be of
    # one of the supported content types - 'application/pdf', 'image/jpeg' or
    # 'image/png'. A success response is returned in JSON.
    #
    # @param id Model Identifier to analyze the document with.
    # @param form_stream A pdf document or image (jpg,png) file to analyze.
    # @param keys [Array<String>] An optional list of known keys to extract the
    # values for.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def analyze_with_custom_model_with_http_info(id, form_stream, keys:nil, custom_headers:nil)
      analyze_with_custom_model_async(id, form_stream, keys:keys, custom_headers:custom_headers).value!
    end

    #
    # Analyze Form
    #
    # Extract key-value pairs from a given document. The input document must be of
    # one of the supported content types - 'application/pdf', 'image/jpeg' or
    # 'image/png'. A success response is returned in JSON.
    #
    # @param id Model Identifier to analyze the document with.
    # @param form_stream A pdf document or image (jpg,png) file to analyze.
    # @param keys [Array<String>] An optional list of known keys to extract the
    # values for.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def analyze_with_custom_model_async(id, form_stream, keys:nil, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'id is nil' if id.nil?
      fail ArgumentError, 'form_stream is nil' if form_stream.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/pdf'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?

      # Set Form Data
      form_data = {}
      form_data['form_stream'] = form_stream.to_s unless form_stream.to_s.nil?

      path_template = 'custom/models/{id}/analyze'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'id' => id},
          query_params: {'keys' => keys.nil? ? nil : keys.join(',')},
          headers: request_headers.merge(custom_headers || {}),
          body: URI.encode_www_form(form_data),
          base_url: request_url
      }
      promise = self.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::AnalyzeResult.mapper()
            result.body = self.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Batch Read Receipt operation. The response contains a field called
    # 'Operation-Location', which contains the URL that you must use for your 'Get
    # Read Receipt Result' operation.
    #
    # @param url [String] Publicly reachable URL of an image.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    #
    def batch_read_receipt(url, custom_headers:nil)
      response = batch_read_receipt_async(url, custom_headers:custom_headers).value!
      nil
    end

    #
    # Batch Read Receipt operation. The response contains a field called
    # 'Operation-Location', which contains the URL that you must use for your 'Get
    # Read Receipt Result' operation.
    #
    # @param url [String] Publicly reachable URL of an image.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def batch_read_receipt_with_http_info(url, custom_headers:nil)
      batch_read_receipt_async(url, custom_headers:custom_headers).value!
    end

    #
    # Batch Read Receipt operation. The response contains a field called
    # 'Operation-Location', which contains the URL that you must use for your 'Get
    # Read Receipt Result' operation.
    #
    # @param url [String] Publicly reachable URL of an image.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def batch_read_receipt_async(url, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'url is nil' if url.nil?

      image_url = ImageUrl.new
      unless url.nil?
        image_url.url = url
      end

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?

      # Serialize Request
      request_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::ImageUrl.mapper()
      request_content = self.serialize(request_mapper,  image_url)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'prebuilt/receipt/asyncBatchAnalyze'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 202
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?

        result
      end

      promise.execute
    end

    #
    # This interface is used for getting the analysis results of a 'Batch Read
    # Receipt' operation. The URL to this interface should be retrieved from the
    # 'Operation-Location' field returned from the 'Batch Read Receipt' operation.
    #
    # @param operation_id [String] Id of read operation returned in the response of
    # a 'Batch Read Receipt' operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [ReadReceiptResult] operation results.
    #
    def get_read_receipt_result(operation_id, custom_headers:nil)
      response = get_read_receipt_result_async(operation_id, custom_headers:custom_headers).value!
      response.body unless response.nil?
    end

    #
    # This interface is used for getting the analysis results of a 'Batch Read
    # Receipt' operation. The URL to this interface should be retrieved from the
    # 'Operation-Location' field returned from the 'Batch Read Receipt' operation.
    #
    # @param operation_id [String] Id of read operation returned in the response of
    # a 'Batch Read Receipt' operation.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def get_read_receipt_result_with_http_info(operation_id, custom_headers:nil)
      get_read_receipt_result_async(operation_id, custom_headers:custom_headers).value!
    end

    #
    # This interface is used for getting the analysis results of a 'Batch Read
    # Receipt' operation. The URL to this interface should be retrieved from the
    # 'Operation-Location' field returned from the 'Batch Read Receipt' operation.
    #
    # @param operation_id [String] Id of read operation returned in the response of
    # a 'Batch Read Receipt' operation.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def get_read_receipt_result_async(operation_id, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'operation_id is nil' if operation_id.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?
      path_template = 'prebuilt/receipt/operations/{operationId}'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'operationId' => operation_id},
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:get, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
        # Deserialize Response
        if status_code == 200
          begin
            parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
            result_mapper = Azure::CognitiveServices::FormRecognizer::V1_0_preview::Models::ReadReceiptResult.mapper()
            result.body = self.deserialize(result_mapper, parsed_response)
          rescue Exception => e
            fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
          end
        end

        result
      end

      promise.execute
    end

    #
    # Read Receipt operation. When you use the 'Batch Read Receipt' interface, the
    # response contains a field called 'Operation-Location'. The
    # 'Operation-Location' field contains the URL that you must use for your 'Get
    # Read Receipt Result' operation.
    #
    # @param image An image stream.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    #
    def batch_read_receipt_in_stream(image, custom_headers:nil)
      response = batch_read_receipt_in_stream_async(image, custom_headers:custom_headers).value!
      nil
    end

    #
    # Read Receipt operation. When you use the 'Batch Read Receipt' interface, the
    # response contains a field called 'Operation-Location'. The
    # 'Operation-Location' field contains the URL that you must use for your 'Get
    # Read Receipt Result' operation.
    #
    # @param image An image stream.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def batch_read_receipt_in_stream_with_http_info(image, custom_headers:nil)
      batch_read_receipt_in_stream_async(image, custom_headers:custom_headers).value!
    end

    #
    # Read Receipt operation. When you use the 'Batch Read Receipt' interface, the
    # response contains a field called 'Operation-Location'. The
    # 'Operation-Location' field contains the URL that you must use for your 'Get
    # Read Receipt Result' operation.
    #
    # @param image An image stream.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def batch_read_receipt_in_stream_async(image, custom_headers:nil)
      fail ArgumentError, 'endpoint is nil' if endpoint.nil?
      fail ArgumentError, 'image is nil' if image.nil?


      request_headers = {}
      request_headers['Content-Type'] = 'application/octet-stream'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = accept_language unless accept_language.nil?

      # Serialize Request
      request_mapper = {
        client_side_validation: true,
        required: true,
        serialized_name: 'Image',
        type: {
          name: 'Stream'
        }
      }
      request_content = self.serialize(request_mapper,  image)

      path_template = 'prebuilt/receipt/asyncBatchAnalyze'

      request_url = @base_url || self.base_url
    request_url = request_url.gsub('{Endpoint}', endpoint)

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = self.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 202
          error_model = JSON.load(response_content)
          fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?

        result
      end

      promise.execute
    end


    private
    #
    # Adds telemetry information.
    #
    def add_telemetry
        sdk_information = 'azure_cognitiveservices_formrecognizer'
        sdk_information = "#{sdk_information}/0.17.2"
        add_user_agent_information(sdk_information)
    end
  end
end
