# frozen_string_literal: true

require 'logger'

module Matterhorn
  MATTERHORN_LOG_LEVELS = ['debug', 'info', 'warn', 'error', 'fatal', 'unknown'].freeze

  class LogClient
    class << self
      def client
        @client ||= begin
          log_client = ::Logger.new(STDOUT)
          log_client.level = ::Logger::INFO
          log_client.formatter = proc do |severity, datetime, progname, msg|
            progname ||= 'matterhorn'
            if !defined?(PROJECT) || PROJECT.nil? || PROJECT.empty?
              "#{datetime.strftime('%H:%M:%S')} [#{progname}] #{severity}: #{msg2str(msg)}\n"
            else
              "#{datetime.strftime('%H:%M:%S')} [#{progname}-worker][#{PROJECT}] #{severity}:  #{msg2str(msg)}\n"
            end
          end
          log_client
        end
      end

      def msg2str(msg)
        case msg
        when ::String
          msg
        when ::Exception
          "#{ msg.message } (#{ msg.class })\n" <<
            (msg.backtrace || []).join("\n")
        else
          msg.inspect
        end
      end

      def method_missing(name, *args, &block)
        return client.send(name, *args, &block) if client.respond_to?(name)
        super
      end

      def respond_to_missing?(name, include_private = false)
        client.respond_to?(name) || super
      end

      MATTERHORN_LOG_LEVELS.each do |level|
        define_method(level) do |*args, &block|
          client.send(level, *args, &block)
        end
      end
    end
  end

  module Logger
    def logger
      Matterhorn::LogClient
    end
    alias log logger
  end
end
