class SimpleXChat::BasicCommandRunner

def initialize(client, commands, prefix)

def initialize(client, commands, prefix)
  @client = client
  @commands = commands.map { |cmd|
    { "#{prefix}#{cmd.name}" => cmd }
  }.reduce({}, &:merge)
  @prefix = prefix
  @logger = Logging.logger
end

def listen(max_backlog_secs: 5.0)

def listen(max_backlog_secs: 5.0)
  loop do
    begin
      break if process_next_event(max_backlog_secs) == :stop
    rescue SimpleXChat::GenericError => e
      @logger.error("[!] Caught error: #{e}")
    rescue => e
      raise e
    end
  end
end

def process_next_event(max_backlog_secs)

def process_next_event(max_backlog_secs)
  chat_msg = @client.next_chat_message(max_backlog_secs: max_backlog_secs)
  if chat_msg == nil
    @logger.warn("Message queue is closed")
    return :stop
  end
  @logger.debug("Chat message: #{chat_msg}")
  msg_text = chat_msg[:msg_text]
  chat_type = chat_msg[:chat_type]
  issuer = chat_msg[:contact]
  issuer_role = chat_msg[:contact_role]
  sender = chat_msg[:sender]
  # Skip automated group messages
  return if issuer == nil
  # Verify if message is a command
  message_items = msg_text.split(" ")
  first_word = message_items[0]
  return if not first_word.start_with?(@prefix)
  # React to all messages we will process
  @client.api_reaction chat_msg[:chat_type], chat_msg[:sender_id], chat_msg[:msg_item_id], emoji: '🚀'
  # Verify if this is a registered command
  command = @commands[first_word]
  if command == nil
    @client.api_send_text_message chat_msg[:chat_type], chat_msg[:sender], "@#{issuer}: Unknown command"
    return
  end
  args = message_items[1..]
  # Run command
  @logger.debug("Validating and executing command '#{command.name}' for: #{chat_type}#{sender} [#{issuer}]: #{msg_text}")
  command.validate_and_execute @client, chat_msg, args
end