class XmppSetDefaultBookmarksJob < ApplicationJob
  queue_as :default

  def perform(user)
    return unless Setting.xmpp_default_rooms.any?
    @user = user
    ejabberd = EjabberdApiClient.new
    ejabberd.private_set user, storage_content
  end

  def storage_content
    bookmarks = ""
    Setting.xmpp_default_rooms.each do |r|
      bookmarks << conference_element(
        jid: r[/<(.+)>/, 1], name: r[/^(.+)\s/, 1], nick: @user.cn,
        autojoin: Setting.xmpp_autojoin_default_rooms
      )
    end

    "<storage xmlns='storage:bookmarks'>#{bookmarks}</storage>"
  end

  def conference_element(jid:, name:, autojoin: false, nick:)
    "<conference jid='#{jid}' name='#{name}' autojoin='#{autojoin.to_s}'><nick>#{nick}</nick></conference>"
  end
end
