/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2010, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.msc.registry;

import org.jboss.msc.service.AbstractServiceListener;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Service registry capable of installing batches of services and enforcing dependency order. 
 *
 * @author John Bailey
 */
public class ServiceRegistry {
    private final ConcurrentMap<ServiceName, ServiceController<?>> registry = new ConcurrentHashMap<ServiceName, ServiceController<?>>();

    private final ServiceContainer serviceContainer;

    public ServiceRegistry(ServiceContainer serviceContainer) {
        this.serviceContainer = serviceContainer;
    }

    public ServiceBatch create() {
        return new ServiceBatch(this);
    }

    /**
     * Install a collection of service definitions into the registry.  Will install the services
     * in dependency order.
     *
     * @param services The service definitions to install
     * @throws ServiceRegistryException If any problems occur resolving the dependencies or adding to the registry.
     */
    void install(Map<ServiceName, ServiceDefinition> services) throws ServiceRegistryException {
        try {
            resolve(services);
        } catch (ResolutionException e) {
            throw new ServiceRegistryException("Failed to resolve dependencies", e);
        }
    }

    /**
     * Recursive depth-first resolution
     *
     * @param serviceDefinitions The list of items to be resolved
     * @throws ResolutionException if any problem occur during resolution
     */
    private void resolve(final Map<ServiceName, ServiceDefinition> serviceDefinitions) throws ServiceRegistryException {
        final Set<ServiceName> visited = new HashSet<ServiceName>();
        for (ServiceDefinition serviceDefinition : serviceDefinitions.values()) {
            resolve(serviceDefinition, serviceDefinitions, visited);
        }
    }

    private ServiceController<?> resolve(final ServiceDefinition serviceDefinition, final Map<ServiceName, ServiceDefinition> serviceDefinitions, final Set<ServiceName> visited) throws ServiceRegistryException {
        ServiceController<?> serviceController = registry.get(serviceDefinition.getName());
        if(serviceController != null)
            return serviceController;

        if (!visited.add(serviceDefinition.getName()))
            throw new CircularDependencyException("Circular dependency discovered: " + visited);
            
        try {
            final ServiceBuilder<Service> builder = serviceContainer.buildService(serviceDefinition.getService());

            for (String dependency : serviceDefinition.getDependencies()) {
                final ServiceName dependencyName = ServiceName.create(dependency);

                ServiceController<?> dependencyController = registry.get(dependencyName);
                if(dependencyController != null) {
                    builder.addDependency(dependencyController);
                    continue;
                }

                final ServiceDefinition dependencyDefinition = serviceDefinitions.get(dependencyName);
                if (dependencyDefinition == null)
                    throw new MissingDependencyException("Missing dependency: " + serviceDefinition.getName() + " depends on " + dependencyName + " which can not be found");

                dependencyController = resolve(dependencyDefinition, serviceDefinitions, visited);
                builder.addDependency(dependencyController);
            }

            // We are resolved.  Lets install
            builder.addListener(new ServiceUnregisterListner(serviceDefinition.getName()));
            serviceController = builder.create();
            if (registry.putIfAbsent(serviceDefinition.getName(), serviceController) != null) {
                throw new ServiceRegistryException("Duplicate service name provided: " + serviceDefinition.getName());
            }
            return serviceController;
        } finally {
            visited.remove(serviceDefinition.getName());
        }

    }

    private class ServiceUnregisterListner extends AbstractServiceListener<Service> {
        private final ServiceName serviceName;

        private ServiceUnregisterListner(ServiceName serviceName) {
            this.serviceName = serviceName;
        }

        @Override
        public void serviceRemoved(ServiceController serviceController) {
            if(!registry.remove(serviceName, serviceController))
                throw new RuntimeException("Removed service [" + serviceName + "] was not unregistered");
        }
    }
}

@@ -3400,166 +3400,60 @@
     
-ServiceController%3C?%3E serviceController = registry.get(serviceDefinition.getName());%0A        if(serviceController != null)%0A            return serviceController
+final ServiceName name = serviceDefinition.getName()
 ;%0A%0A 
@@ -3480,37 +3480,16 @@
 add(
-serviceDefinition.getN
+n
 ame
-(
 ))
-)
+ %7B
 %0A   
@@ -3590,20 +3590,18 @@
         
-    
+%7D%0A
 %0A       
@@ -3599,32 +3599,125 @@
 %0A%0A        try %7B%0A
+            final ConcurrentMap%3CServiceName, ServiceController%3C?%3E%3E registry = this.registry;%0A
             fina
@@ -4084,16 +4084,17 @@
       if
+ 
 (depende
@@ -4107,17 +4107,17 @@
 troller 
-!
+=
 = null) 
@@ -4126,118 +4126,8 @@
     
-                builder.addDependency(dependencyController);%0A                    continue;%0A                %7D%0A%0A
     
@@ -4233,32 +4233,36 @@
                 
+   
+ 
 if (dependencyDe
@@ -4279,16 +4279,20 @@
 = null)%0A
+    
         
@@ -4369,35 +4369,12 @@
 %22 + 
-serviceDefinition.getN
+n
 ame
-()
  + %22
@@ -4434,17 +4434,20 @@
 ound%22);%0A
-%0A
+    
         
@@ -4529,32 +4529,50 @@
 ions, visited);%0A
+                %7D%0A
                 
@@ -4742,38 +4742,16 @@
 ner(
-serviceDefinition.getN
+n
 ame
-(
 ))
-)
 ;
+%0A
 %0A   
@@ -4758,16 +4758,43 @@
         
+ final ServiceController%3C?%3E
  service
@@ -4865,35 +4865,12 @@
 ent(
-serviceDefinition.getN
+n
 ame
-()
 , se
@@ -4990,35 +4990,12 @@
 %22 + 
-serviceDefinition.getN
+n
 ame
-()
 );%0A 
@@ -5096,35 +5096,12 @@
 ove(
-serviceDefinition.getN
+n
 ame
-()
 );%0A 

Trim off a few ns, possibly