package com.hwangjr.rxbus;

import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
import timber.log.Timber;

@Deprecated
public class RxBusOlder {
    private static final boolean DEBUG = true;

    private static RxBusOlder mInstance;

    private ConcurrentHashMap<Object, List<Subject>> mSubjectsMapper = new ConcurrentHashMap<>();

    public static synchronized RxBusOlder instance() {
        if (mInstance == null) {
            mInstance = new RxBusOlder();
        }
        return mInstance;
    }

    private RxBusOlder() {
    }

    public <T> Observable<T> register(@NonNull Object tag, @NonNull Class<T> clazz) {
        List<Subject> subjectList = mSubjectsMapper.get(tag);
        if (subjectList == null) {
            subjectList = new ArrayList<>();
            mSubjectsMapper.put(tag, subjectList);
        }

        Subject<T, T> subject = PublishSubject.create();
        subjectList.add(subject);
        if (DEBUG) {
            Timber.d("[register] mSubjectsMapper: " + mSubjectsMapper);
        }
        return subject;
    }

    public void unregister(@NonNull Object tag, @NonNull Observable observable) {
        List<Subject> subjects = mSubjectsMapper.get(tag);
        if (subjects != null) {
            subjects.remove(observable);
            if (subjects.isEmpty()) {
                mSubjectsMapper.remove(tag);
            }
            if (DEBUG) {
                Timber.d("[unregister] mSubjectsMapper: " + mSubjectsMapper);
            }
        }
    }

    public void post(@NonNull Object tag, @NonNull Object content) {
        List<Subject> subjects = mSubjectsMapper.get(tag);
        if (subjects != null && !subjects.isEmpty()) {
            for (Subject subject : subjects) {
                subject.onNext(content);
            }
        }
        if (DEBUG) {
            Timber.d("[send] mSubjectsMapper: " + mSubjectsMapper);
        }
    }

}

@@ -217,24 +217,62 @@
 ishSubject;%0A
+import rx.subjects.SerializedSubject;%0A
 import rx.su
@@ -430,17 +430,17 @@
 usOlder 
-m
+s
 Instance
@@ -608,17 +608,17 @@
     if (
-m
+s
 Instance
@@ -641,17 +641,17 @@
         
-m
+s
 Instance
@@ -696,17 +696,17 @@
  return 
-m
+s
 Instance
@@ -1070,16 +1070,40 @@
 bject = 
+new SerializedSubject%3C%3E(
 PublishS
@@ -1113,16 +1113,19 @@
 ect.
+%3CT%3E
 create()
 ;%0A  
@@ -1120,16 +1120,17 @@
 create()
+)
 ;%0A      

convert PublishSubject to SerializedSubject