package tw.jwzhuang.jtools;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;
import java.util.List;

public class HandlerManager implements HandlerWatcherListener {
    private static final HandlerManager ourInstance = new HandlerManager();
    private EventBus eventBus = EventBus.builder().build();
    public static HandlerManager shared() {
        return ourInstance;
    }

    private List<HandlerWatcher> watchers;

    private HandlerManager() {
        watchers = new LinkedList<>();
    }

    public void resume() {
        if (watchers.size() > 0) {
            this.eventBus.post(HandlerEvent.Resume.build());
        }
    }

    public void pause() {
        if (watchers.size() > 0) {
            this.eventBus.post(HandlerEvent.Pause.build());
        }
    }

//    public void makeHandler(HandlerTask task){
//        HandlerWatcher watcher = makeWatcher()
//                .runTask(task);
//    }

    public HandlerWatcher makeHandler(HandlerTask task, int secs){
        return makeWatcher().runTask(task, secs * 1000);
    }

    private HandlerWatcher makeWatcher(){
        HandlerWatcher watcher = HandlerWatcher.builder(this.eventBus).setListener(this);
        this.watchers.add(watcher);
        return watcher;
    }

    //<editor-fold desc="HandlerWatcherListener">
    @Override
    public void complete(HandlerWatcher watcher) {
        synchronized (this.watchers){
            System.out.println("zzzz: " + this.watchers.size());
            this.watchers.remove(watcher);
            System.out.println("zzzz: " + this.watchers.size());
        }
    }
    //</editor-fold>
}


@@ -81,26 +81,25 @@
 va.util.
-LinkedList
+Hashtable
 ;%0Aimport
@@ -109,20 +109,19 @@
 va.util.
-List
+Map
 ;%0A%0Apubli
@@ -406,21 +406,28 @@
 private 
-List%3C
+Map%3CString, 
 HandlerW
@@ -503,18 +503,17 @@
 new 
-LinkedList
+Hashtable
 %3C%3E()
@@ -1030,94 +1030,393 @@
 make
-Watcher().runTask(task, secs * 1000);%0A    %7D%0A%0A    private HandlerWatcher makeWatcher()%7B
+Handler(task, secs, %22Default%22);%0A    %7D%0A%0A    public HandlerWatcher makeHandler(HandlerTask task, int secs, String token)%7B%0A        return makeWatcher(token).runTask(task, secs * 1000);%0A    %7D%0A%0A    private HandlerWatcher makeWatcher(String token)%7B%0A%0A        if (watchers.containsKey(token))%7B%0A            HandlerWatcher watcher = watchers.get(token);%0A            watcher.destroy();%0A        %7D%0A
 %0A   
@@ -1528,12 +1528,19 @@
 ers.
-add(
+put(token, 
 watc
@@ -1745,166 +1745,36 @@
     
-System.out.println(%22zzzz: %22 + this.watchers.size());%0A            this.watchers.remove(watcher);%0A            System.out.println(%22zzzz: %22 + this.watchers.size()
+this.watchers.remove(watcher
 );%0A 

fix bug