/*
 * 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.support;

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

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

import com.sun.appserv.management.base.AMXDebug;
import com.sun.appserv.management.base.Container;
import com.sun.appserv.management.base.Util;
import com.sun.appserv.management.client.ProxyFactory;
import com.sun.enterprise.management.support.ObjectNames;

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 static com.sun.appserv.management.base.XTypes.SERVER_REF_CONFIG;
import com.sun.appserv.management.config.DeployedItemRefConfig;
import com.sun.appserv.management.config.ServerRefConfig;
import com.sun.appserv.management.config.ClusterConfig;
import com.sun.appserv.management.config.ServerConfig;
import com.sun.appserv.management.config.ClusteredServerConfig;
import com.sun.appserv.management.config.StandaloneServerConfig;
import com.sun.appserv.management.config.LBConfig;
/**
 * A class that triggers forming LB monitoring tree whenever a new <server-ref>
 * gets added to a <lb-config> or <cluster> elements. The registration logic 
 * Determines parent object <lb-config> or <cluster>.
 *
 * If <lb-config> i.e. the server-ref is for a standalone server 
 * 1. get ALL standalone <server> elements
 * 2. locate the referring <load-balancer> elements and fetch corresponding 
 *    root LoadBalancerMonitors 
 * 3. create LoadBalancerClusterMonitor and its child LoadBalancerServerMonitor 
 *    and create the rest of the monitoring tree under this LoadBalancerServerMonitor 
 *    as governed by the structure of the <server> element
 *
 * If <cluster> i.e. the server-ref is for a clustered server 
 * 1. fetch <lb-configs elements that have reference to this <cluster> 
 * 2. fetch root LoadBalancerMonitors for the <lb-config> elements found in 
 *    step 1. (this happens via <load-balancer> elements
 * 3. fetch ONLY those LoadBalancerClusterMonitors that have the same name as the 
 *    name of the cluster of the clustered server 
 * 4. create child LoadBalancerServerMonitors under the LoadBalancerClusterMonitors 
 *    found in step 3 and create the rest of the monitoring tree under this 
 *    LoadBalancerServerMonitor as governed by the structure of the <server> element
 *
 * @see LoadBalancerClusterRefRegistrationListener
 * @see LoadBalancerApplicationRefRegistrationListener
 * @see LoadBalancerRegistrationListener
 */
public class LoadBalancerServerRefRegistrationListener 
    extends LBBaseMBeanRegistrationListener {  
    
    public LoadBalancerServerRefRegistrationListener(MBeanServer mBeanServer)
        throws InstanceNotFoundException, IOException {
        super(mBeanServer);
    }

    protected void mbeanRegistered(final ObjectName objectName) {
        try {
            if (SERVER_REF_CONFIG.equals(Util.getJ2EEType(objectName))) {
                
                ServerRefConfig serverRefConfig = 
                    ProxyFactory.getInstance(getConn()).getProxy(objectName, ServerRefConfig.class);
                String serverName = serverRefConfig.getRef();
                Container container = serverRefConfig.getContainer();
                
                Map<String, ServerConfig> serverConfigMap = new HashMap<String, ServerConfig>();

                if (container instanceof LBConfig) {
                    //get ALL standalone <server> elements
                    Map<String,StandaloneServerConfig> sserverConfigMap = 
                        getDomainConfig().getStandaloneServerConfigMap();
                    
                    //doing the following to enable reuse of the 
                    //registerLoadBalancerServerMonitorTree base class method
                    for (String key : sserverConfigMap.keySet()) {
                        serverConfigMap.put(
                            key, (ServerConfig)sserverConfigMap.get(key));
                    }
                    
                    List<LoadBalancerMonitor> loadBalancerMonitorList =
                        fetchLBMonitoringRoots((LBConfig)container);
                    
                    for (LoadBalancerMonitor lbm : loadBalancerMonitorList) {
                        LoadBalancerClusterMonitor lbcm =
                            registerLoadBalancerClusterMonitor(
                                lbm, serverName);
                        registerLoadBalancerServerMonitorTree(
                            lbcm, serverConfigMap, serverName);
                    } //end for (LoadBalancerMonitor : loadBalancerMonitorList)
                } //end if (container instanceof LBConfig)

                else  if (container instanceof ClusterConfig) {
                    //get ALL clustered <server> elements
                    Map<String,ClusteredServerConfig> cserverConfigMap = 
                        getDomainConfig().getClusteredServerConfigMap(); 
                    
                    //doing the following to enable reuse of the 
                    //registerLoadBalancerServerMonitorTree base class method
                    for (String key : cserverConfigMap.keySet()) {
                        serverConfigMap.put(
                            key, (ServerConfig)cserverConfigMap.get(key));
                    }

                    Collection<LBConfig> affectedLBConfigArr = 
                        fetchLBConfigs(((ClusterConfig)container).getName(), true);
                    
                    for (LBConfig lbConfig : affectedLBConfigArr) {
                        List<LoadBalancerMonitor> monitoringRoots = 
                            fetchLBMonitoringRoots(lbConfig);
                        List<LoadBalancerClusterMonitor> clusterMonitors = 
                            fetchLoadBalancerClusterMonitors(monitoringRoots, 
                                ((ClusterConfig)container).getName());
                        
                        for (LoadBalancerClusterMonitor lbcm : clusterMonitors) { 
                            registerLoadBalancerServerMonitorTree(
                                lbcm, serverConfigMap, serverName);
                        }
                    }
                }
            }
	} catch (Exception ex) {
            logWarning(
                "LoadBalancerServerRefRegistrationListener" +
                " mbeanRegistered failed. Exception = ", ex);	
	}
    }
}
