/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
 
/*
 */

package com.sun.enterprise.management.config;

import com.sun.enterprise.management.support.LBDeregistrationUtil;
import javax.management.ObjectName;

import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.IOException;

import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import com.sun.appserv.management.base.XTypes;
import com.sun.enterprise.management.config.AMXConfigImplBase;
import com.sun.enterprise.management.support.Delegate;
import com.sun.enterprise.management.support.ObjectNames;

import static com.sun.appserv.management.base.XTypes.LOAD_BALANCER;
import static com.sun.appserv.management.base.XTypes.LOAD_BALANCER_MONITOR;
import static com.sun.appserv.management.base.AMX.J2EE_TYPE_KEY;
import static com.sun.appserv.management.base.AMX.NAME_KEY;
import static com.sun.appserv.management.base.AMX.JMX_DOMAIN;

import com.sun.appserv.management.base.Util;
import com.sun.appserv.management.base.AMXDebug;
import com.sun.appserv.management.monitor.LoadBalancerMonitor;  
import com.sun.appserv.management.monitor.LoadBalancerClusterMonitor;
import com.sun.appserv.management.monitor.LoadBalancerServerMonitor;
import com.sun.appserv.management.monitor.LoadBalancerApplicationMonitor;
import com.sun.appserv.management.monitor.LoadBalancerContextRootMonitor;
import com.sun.appserv.management.config.DeployedItemRefConfig;
import com.sun.appserv.management.config.ClusterRefConfig;
import com.sun.appserv.management.config.ClusterConfig;
import com.sun.appserv.management.config.ServerRefConfig;
import com.sun.appserv.management.config.ServerConfig;
import com.sun.appserv.management.config.LoadBalancerConfig;
import com.sun.appserv.management.config.LBConfig;
import com.sun.appserv.management.client.ProxyFactory;
/**
	Configuration for the &lt;server-ref&gt; element.
*/
public final class ServerRefConfigImpl extends AMXConfigImplBase 
        implements ConfigFactoryCallback
{
	// implements ServerRefConfig
    ServerRefDeregistrationHelper mHelper = null;
    
    public ServerRefConfigImpl(final Delegate delegate)
    {
        super(delegate);
    }


    public ObjectName getHealthCheckerConfigObjectName()
    {
        return(getContaineeObjectName(XTypes.HEALTH_CHECKER_CONFIG));
    }

    private HealthCheckerConfigFactory getHealthCheckerConfigFactory() {
        return new HealthCheckerConfigFactory(this);
    }

        public ObjectName
    createHealthCheckerConfig(
        String url, 
        String intervalInSeconds,
        String timeoutInSeconds)
    {
        return getHealthCheckerConfigFactory().create(
            url,intervalInSeconds, timeoutInSeconds);
    }

    public void removeHealthCheckerConfig(final String name)
    {
        final ObjectName item = getHealthCheckerConfigObjectName();
        getHealthCheckerConfigFactory().remove(item);
    }

    protected void unregisterMisc() {
        try {
            mHelper = new ServerRefDeregistrationHelper(
                            getName(), getMBeanServer());
        } catch (Exception ex) {
            logWarning("ServerRefConfig unregisterMisc failed. " +
                    "ServerRefDeregistrationHelper creation failed");
        }                
    }    

    public void postDeregister() {
        super.postDeregister();
        try {            
            if (getContainer() instanceof LBConfig) {
                //collect all load-balancer elements which refer
                //to this lb-config
                String lbConfigName = ((LBConfig)getContainer()).getName();
                Map<String,LoadBalancerConfig> relevantLoadBalancerConfigMap = 
                     mHelper.fetchLoadBalancerConfigs((LBConfig)getContainer());
                mHelper.unregisterMonitors(relevantLoadBalancerConfigMap);
            } else if (getContainer() instanceof ClusterConfig) {
                String clusterName = ((ClusterConfig)getContainer()).getName();
                Map<String,LoadBalancerConfig> relevantLoadBalancerConfigMap =
                    mHelper.fetchLoadBalancerConfigs((ClusterConfig)getContainer());
                mHelper.unregisterMonitors(clusterName, relevantLoadBalancerConfigMap);
            }
            mHelper = null;
        } catch (Exception ex) {
            logWarning("ServerRefConfig postDeregistration failed. " +
                    "Load Balancer Monitoring MBeans might be lying around");
        }                
    }

    private class ServerRefDeregistrationHelper {    

        final static String J2EE_TYPE = "j2eeType";
        final ObjectNames objectNames = ObjectNames.getInstance(JMX_DOMAIN);    
        String serverName = null;
        MBeanServer mbs = null;

        public ServerRefDeregistrationHelper(String serverName, MBeanServer mbs) {
            this.mbs = mbs;
            this.serverName = serverName;
        }        
        
        void unregisterMonitors(Map<String,LoadBalancerConfig>  
            relevantLoadBalancerConfigMap) throws JMException {
            
            unregisterMonitors(serverName, relevantLoadBalancerConfigMap);
        }
        
        void unregisterMonitors(String clusterName,
            Map<String,LoadBalancerConfig>  relevantLoadBalancerConfigMap) 
            throws JMException {

            for (String loadBalancerName : relevantLoadBalancerConfigMap.keySet()) {
               LoadBalancerMonitor loadBalancerMonitor = 
                    LBDeregistrationUtil.getInstance(mbs).
                       fetchLBMonitoringRoot(loadBalancerName);

               Map<String,LoadBalancerClusterMonitor> loadBalancerClusterMonitorMap =
                   loadBalancerMonitor.getLoadBalancerClusterMonitorMap();

               LoadBalancerClusterMonitor loadBalancerClusterMonitor = 
                   loadBalancerClusterMonitorMap.get(clusterName);

               //loadBalancerServerMonitorMap will have only one element for every
               //standalone server as it is is wrapped up in a default cluster
               Map<String,LoadBalancerServerMonitor> loadBalancerServerMonitorMap =
                    loadBalancerClusterMonitor.getLoadBalancerServerMonitorMap();

               for (String serverName : loadBalancerServerMonitorMap.keySet()) {
                   LoadBalancerServerMonitor loadBalancerServerMonitor = 
                       loadBalancerServerMonitorMap.get(serverName);
                   Map<String,LoadBalancerApplicationMonitor> 
                       loadBalancerApplicationMonitorMap =
                           loadBalancerServerMonitor
                           .getLoadBalancerApplicationMonitorMap();

                   for (String appName : loadBalancerApplicationMonitorMap.keySet()) {
                        LoadBalancerApplicationMonitor loadBalancerApplicationMonitor = 
                            loadBalancerApplicationMonitorMap.get(appName);
                        Map<String,LoadBalancerContextRootMonitor> 
                            lbcrmm = loadBalancerApplicationMonitor
                                .getLoadBalancerContextRootMonitorMap();
                       for (String ctxRootName : lbcrmm.keySet()) {
                            LoadBalancerContextRootMonitor loadBalancerContextRootMonitor = 
                                lbcrmm.get(ctxRootName);
                            ObjectName loadBalancerContextRootMonitorObjName = 
                                Util.getObjectName(loadBalancerContextRootMonitor);
                            mbs.unregisterMBean(loadBalancerContextRootMonitorObjName);
                        }

                        ObjectName loadBalancerApplicationMonitorObjName = 
                        Util.getObjectName(loadBalancerApplicationMonitor);
                        mbs.unregisterMBean(
                            loadBalancerApplicationMonitorObjName);
                    }

                    ObjectName loadBalancerServerMonitorObjName = 
                        Util.getObjectName(loadBalancerServerMonitor);
                        mbs.unregisterMBean(loadBalancerServerMonitorObjName);
                }

                ObjectName loadBalancerClusterMonitorObjName = 
                    Util.getObjectName(loadBalancerClusterMonitor);
                mbs.unregisterMBean(loadBalancerClusterMonitorObjName);
            }
        }
        
        Map<String,LoadBalancerConfig> fetchLoadBalancerConfigs(
            LBConfig lbConfig) {
            Map<String, LBConfig> lbConfigMap = new HashMap<String, LBConfig>();
            lbConfigMap.put(lbConfig.getName(), lbConfig);
            return fetchLoadBalancerConfigs(lbConfigMap);
        }        
        
        Map<String,LoadBalancerConfig> fetchLoadBalancerConfigs(
            ClusterConfig clusterConfig) {

            String clusterName = clusterConfig.getName();
            //collect all cluster-ref elements which refer to this cluster
            Map<String,LBConfig> allLBConfigMap =
                 getDomainRoot().getDomainConfig().getLBConfigMap();

            Map<String, LBConfig> relevantLBConfigMap = new HashMap<String, LBConfig>();
            for (String lbConfigName : allLBConfigMap.keySet()) { 
                LBConfig lbConfig = allLBConfigMap.get(lbConfigName);
                Map<String,ClusterRefConfig> clusterRefConfigMap = 
                    lbConfig.getClusterRefConfigMap();
                for (String clusterRef : clusterRefConfigMap.keySet()) { 
                    if (clusterRef.equals(clusterName)) {
                        relevantLBConfigMap.put(lbConfigName, lbConfig);
                        break;
                    }
                }
            }
            return fetchLoadBalancerConfigs(relevantLBConfigMap);
        } 
        
        private Map<String,LoadBalancerConfig> fetchLoadBalancerConfigs(
            Map<String, LBConfig> lbConfigMap) {

            Map<String,LoadBalancerConfig> relevantLoadBalancerConfigMap =
                new HashMap<String,LoadBalancerConfig>();

            for (String lbConfigName : lbConfigMap.keySet()) {
                //collect all load-balancer elements which refer to this lb-config
                Map<String,LoadBalancerConfig> allLoadBalancerConfigMap =
                     getDomainRoot().getDomainConfig().getLoadBalancerConfigMap();


                for (String loadBalancerName : allLoadBalancerConfigMap.keySet()) {
                    LoadBalancerConfig loadBalancerConfig = 
                        allLoadBalancerConfigMap.get(loadBalancerName);
                    if (loadBalancerConfig.getLbConfigName().equals(lbConfigName))
                        relevantLoadBalancerConfigMap.put(
                            loadBalancerName, loadBalancerConfig);
                }
            }
            return relevantLoadBalancerConfigMap;
        }        

    }
}