package chat.rocket.android.service.internal;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import chat.rocket.persistence.realm.RealmHelper;
import chat.rocket.android.service.DDPClientRef;
import chat.rocket.android.service.Registrable;
import chat.rocket.android.service.ddp.stream.StreamRoomMessage;

/**
 * wrapper for managing stream-notify-message depending on RocketChatCache.
 */
public class StreamRoomMessageManager implements Registrable {
  private final Context context;
  private final String hostname;
  private final RealmHelper realmHelper;
  private final DDPClientRef ddpClientRef;
  private final AbstractRocketChatCacheObserver cacheObserver;
  private final Handler handler;
  private StreamRoomMessage streamRoomMessage;

  public StreamRoomMessageManager(Context context, String hostname,
                                  RealmHelper realmHelper, DDPClientRef ddpClientRef) {
    this.context = context;
    this.hostname = hostname;
    this.realmHelper = realmHelper;
    this.ddpClientRef = ddpClientRef;

    cacheObserver = new AbstractRocketChatCacheObserver(context, realmHelper) {
      @Override
      protected void onRoomIdUpdated(String roomId) {
        unregisterStreamNotifyMessageIfNeeded();
        registerStreamNotifyMessage(roomId);
      }
    };
    handler = new Handler(Looper.myLooper());
  }

  private void registerStreamNotifyMessage(String roomId) {
    handler.post(() -> {
      streamRoomMessage = new StreamRoomMessage(context, hostname, realmHelper, ddpClientRef, roomId);
      streamRoomMessage.register();
    });
  }

  private void unregisterStreamNotifyMessageIfNeeded() {
    handler.post(() -> {
      if (streamRoomMessage != null) {
        streamRoomMessage.unregister();
        streamRoomMessage = null;
      }
    });
  }

  @Override
  public void register() {
    cacheObserver.register();
  }

  @Override
  public void unregister() {
    unregisterStreamNotifyMessageIfNeeded();
    cacheObserver.unregister();
  }
}

@@ -126,16 +126,60 @@
 ooper;%0A%0A
+import chat.rocket.android.RocketChatCache;%0A
 import c
@@ -216,24 +216,24 @@
 ealmHelper;%0A
-
 import chat.
@@ -772,24 +772,73 @@
 er handler;%0A
+  private final RocketChatCache rocketChatCache;%0A
   private St
@@ -1160,16 +1160,73 @@
 ientRef;
+%0A    this.rocketChatCache = new RocketChatCache(context);
 %0A%0A    ca
@@ -2017,24 +2017,24 @@
 egister() %7B%0A
-
     cacheObs
@@ -2047,24 +2047,192 @@
 register();%0A
+    String selectedRoomId = rocketChatCache.getSelectedRoomId();%0A    if (selectedRoomId == null) %7B%0A      return;%0A    %7D%0A    registerStreamNotifyMessage(selectedRoomId);%0A
   %7D%0A%0A  @Over

Check if user is currently viewing any room by looking at the cache and if so, register to the selected room message stream