/**
 * Copyright 2015-2016 Red Hat, Inc, and individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.wildfly.swarm.topology.runtime;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.jboss.msc.service.ServiceName;
import org.wildfly.swarm.topology.Topology;
import org.wildfly.swarm.topology.TopologyListener;

/**
 * @author Bob McWhirter
 */
public class TopologyManager implements Topology {

    public static final ServiceName SERVICE_NAME = ServiceName.of("swarm", "topology");

    public static final TopologyManager INSTANCE = new TopologyManager();

    private List<TopologyListener> listeners = new ArrayList<>();

    private List<Registration> registrations = new ArrayList<>();

    public void addListener(TopologyListener listener) {
        this.listeners.add(listener);
    }

    public void removeListener(TopologyListener listener) {
        this.listeners.remove(listener);
    }

    private void fireListeners() {
        this.listeners.forEach((e) -> {
            e.onChange(this);
        });
    }

    public synchronized Set<Registration> registrationsForSourceKey(String sourceKey) {
        Set<Registration> result = Collections.unmodifiableSet(
                this.registrations.stream()
                        .filter(e -> e.getSourceKey().equals(sourceKey))
                        .collect(Collectors.toSet())
        );
        return result;
    }

    public synchronized Set<Registration> registrationsForService(String name) {
        Set<Registration> result = Collections.unmodifiableSet(
                this.registrations.stream()
                        .filter(e -> e.getName().equals(name))
                        .collect(Collectors.toSet())
        );

        return result;
    }

    public synchronized void register(Registration registration) {
        if (!this.registrations.contains(registration)) {
            this.registrations.add(registration);
            fireListeners();
        }
    }

    public synchronized void unregister(Registration registration) {
        boolean removed = this.registrations.removeIf(e -> e.equals(registration));
        if (removed) {
            fireListeners();
        }
    }

    public synchronized void unregisterAll(String sourceKey) {
        boolean removed = this.registrations.removeIf(e -> e.getSourceKey().equals(sourceKey));
        if (removed) {
            fireListeners();
        }
    }

    public synchronized void unregisterAll(String sourceKey, String name) {
        boolean removed = this.registrations.removeIf(e -> e.getSourceKey().equals(sourceKey) && e.getName().equals(name));
        if (removed) {
            fireListeners();
        }
    }

    @Override
    public synchronized Map<String, List<Entry>> asMap() {
        Map<String, List<Entry>> map = new HashMap<>();

        for (Registration registration : this.registrations) {
            for (Registration.EndPoint endPoint : registration.endPoints(Registration.EndPoint.Visibility.PUBLIC)) {
                List<Entry> list = map.get(registration.getName());
                if (list == null) {
                    list = new ArrayList<>();
                    map.put(registration.getName(), list);
                }
                list.add(endPoint);
            }
        }

        return map;
    }

}

@@ -817,16 +817,93 @@
 il.Set;%0A
+import java.util.concurrent.Executor;%0Aimport java.util.concurrent.Executors;%0A
 import j
@@ -1454,29 +1454,108 @@
 %3C%3E();%0A%0A    p
-ublic
+rivate Executor executor = Executors.newFixedThreadPool(2);%0A%0A    public synchronized
  void addLis
@@ -1645,16 +1645,29 @@
  public 
+synchronized 
 void rem
@@ -1802,67 +1802,368 @@
     
-this.listeners.forEach((e) -%3E %7B%0A            e.onChange(this
+List%3CTopologyListener%3E currentListeners = new ArrayList%3C%3E();%0A        currentListeners.addAll( this.listeners );%0A        currentListeners.forEach((e) -%3E %7B%0A            executor.execute( ()-%3E%7B%0A                try %7B%0A                    e.onChange(this);%0A                %7D catch (Throwable t) %7B%0A                    removeListener(e);%0A                %7D%0A            %7D
 );%0A 

Handle threading & errors better around TopologyListeners/SSE