# -*- encoding: utf-8 -*-

require 'async_logger'
require 'atomic'
require 'protocol_buffers'
require 'protocol_buffers_require'
require 'lazy_loader'

ProtocolBuffersRequire.require_dirs(File.expand_path(File.join(File.dirname(__FILE__), "..", "ext", "proto", "ourpc_proto")))

require 'thread'

require 'ourpc/base_codec'
require 'ourpc/base_transport'
require 'ourpc/client'
require 'ourpc/error'
require 'ourpc/server_handler'

module Ourpc

  @@lock = Mutex.new
  @@type_checking = false
  @@logger = ::AsyncLogger.create
  @@logger_enabled = true
  @@log_errors_only = false
  @@log_latency_threshold_ms = nil

  # Turn type checking on or off.
  #
  # Type checking is on by default.
  #
  # @param [true, false] type_checking true to turn type checking on, false otherwise
  # @return [nil]
  def self.type_checking=(type_checking)
    @@lock.synchronize do
      @@type_checking = type_checking
      nil
    end
  end

  # @return [true] if type checking is on
  def self.type_checking?
    @@type_checking
  end

  def self.logger
    @@logger
  end

  # overall control, if not enabled, nothing is logged
  def self.logger_enabled
    @@logger_enabled
  end

  def self.logger_enabled=(ilogger_enabled)
    @@lock.synchronize do
      raise ArgumentError.new("logger_enabled being set to true when log_errors_only is true") if ilogger_enabled && @@log_errors_only
      @@logger_enabled = ilogger_enabled
    end
    nil
  end

  # log only errors, must have logger_enabled set to true
  def self.log_errors_only
    @@log_errors_only
  end

  def self.log_errors_only=(ilog_errors_only)
    @@lock.synchronize do
      raise ArgumentError.new("log_errors_only being set to true when logger_enabled is false") if ilog_errors_only && !@@logger_enabled
      @@log_errors_only = ilog_errors_only
    end
    nil
  end

  # log non-error responses above a certain threshold, must have both logger_enabled and log_errors_only set to true
  def self.log_latency_threshold_ms
    @@log_latency_threshold_ms
  end

  def self.log_latency_threshold_ms=(ilog_latency_threshold_ms)
    @@lock.synchronize do
      raise ArgumentError.new("log_latency_threshold_ms being set to non-nil when logger_enabled is false") if ilog_latency_threshold_ms != nil && !@@logger_enabled
      raise ArgumentError.new("log_latency_threshold_ms being set to non-nil when log_errors_only is false") if ilog_latency_threshold_ms != nil && !@@log_errors_only
      @@log_latency_threshold_ms = ilog_latency_threshold_ms
    end
    nil
  end
end
