/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library 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 any later version.
 *
 * This library 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: CmiCluster.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.management.domain.cluster.cmi;


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

import org.objectweb.util.monolog.api.BasicLevel;
import org.ow2.jonas.lib.management.domain.cluster.BaseCluster;
import org.ow2.jonas.lib.management.domain.cluster.ClusterMember;
import org.ow2.jonas.lib.management.domain.proxy.server.ServerProxy;
import org.ow2.jonas.lib.util.JonasObjectName;

/**
 * Implements Cmi Cluster MBean
 * @author Philippe Durieux
 */
public class CmiCluster extends BaseCluster implements CmiClusterMBean {

    /**
     * The type of Cluster, that is part of the MBean ObjectName
     */
    protected String type = "CmiCluster";

    /**
     * mcast port
     */
    protected int mcastPort;

    /**
     * mcast addr
     */
    protected String mcastAddr;

    /**
     * protocol used
     */
    protected String protocol;

    /**
     * This configuration information is provided by a CMI MBean.
     * Every member has a CMI MBean registered in its MBeanServer
     */
    protected int delayToRefresh;

    /**
     * CMI cluster constructor
     * @param cf ClusterFactory
     * @throws JMException could not create MBean instance
     */
    public CmiCluster(final CmiClusterFactory cf) throws JMException {
        super(cf);
    }

    @Override
    public ClusterMember createClusterMember(final String svname, final ServerProxy proxy) {
        return new CmiClusterMember(svname, proxy);
    }

    // --------------------------------------------------------------------------
    // Other public methods
    // --------------------------------------------------------------------------

    /**
     * @return the mcast port
     */
    public int getMcastPort() {
        return mcastPort;
    }

    /**
     * Set the multicast port
     */
    public void setMcastPort(final int port) {
        mcastPort = port;
    }

    /**
     * @return the mcast addr
     */
    public String getMcastAddr() {
        return mcastAddr;
    }

    /**
     * Set the multicast addr
     */
    public void setMcastAddr(final String addr) {
        mcastAddr = addr;
    }

    /**
     * @return the protocol
     */
    public String getProtocol() {
        return protocol;
    }

    /**
     * Set the protocol.
     */
    public void setProtocol(final String protocol) {
        this.protocol = protocol;
    }

    /**
     * @return The String type to be put in the ObjectName
     */
    @Override
    public String getType() {
        return type;
    }

    /**
     * Add a CMI Server to the list of the Cluster
     * Make link between the member and the ServerProxy.
     * @param serverName name of the managed server which corresponds to a Tomcat session replication cluster member
     * @param proxy The ServerProxy related object.
     * @return True if correctly added in the List.
     */
    public boolean addCmiServer(final String serverName, final ServerProxy proxy) {

        // create the CmiClusterMember instance ( = a jonas server)
        CmiClusterMember cmi = new CmiClusterMember(serverName, proxy);

        // Add this member if not already there
        boolean added = addMember(cmi);
        if (added) {
            // Build the ObjectName and register MBean
            try {
                ObjectName on = JonasObjectName.clusterMember(domainName, serverName, getType(), name);
                cmi.setObjectName(on);
                MBeanServer mbeanServer = jmx.getJmxServer();
                if (mbeanServer.isRegistered(on)) {
                    mbeanServer.unregisterMBean(on);
                }
                mbeanServer.registerMBean(cmi, on);
            } catch (JMException e) {
                logger.log(BasicLevel.WARN, "Cannot register tomcat " + serverName + ": " + e);
            }
        }
        return added;
    }

    /**
     * Update dynamic info for this cluster.
     * Currently only delayToRefresh can change during runtime.
     */
    public void getMonitoringInfo() {
        ServerProxy proxy = getRunningServerProxy();
        if (proxy != null) {
            // Found a running memeber's proxy
            ObjectName cmiOn = null;
            try {
                cmiOn = JonasObjectName.cmiServer(proxy.getDomain(), proxy.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.delayToRefresh = getDelayToRefresh(cmiOn);
        }
    }

    /**
     * Get the value of 'delayToRefresh' attribute.
     * @return delayToRefresh MBean attribute's value
     */
    public int getDelayToRefresh() {
        return delayToRefresh;
    }

    /**
     * Set new value for the 'delayToRefresh' attribute and propagate
     * this value to one CMI MBean corresponding to a cluster member.
     * @param delayToRefresh new value for the 'delayToRefresh' attribute
     */
    public void setDelayToRefresh(final int delayToRefresh) {
        ServerProxy proxy = getRunningServerProxy();
        if (proxy != null) {
            // Found a running memeber's proxy
            ObjectName cmiOn = null;
            try {
                cmiOn = JonasObjectName.cmiServer(proxy.getDomain(), proxy.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            setDelayToRefresh(cmiOn, delayToRefresh);
            this.delayToRefresh = delayToRefresh;
        }
    }

    /**
     * Get the 'DelayToRefresh' from a member's cmi MBean.
     * @param cmiOn CMI MBean's ObjectName
     * @return 'DelayToRefresh' attribute value
     */
    private int getDelayToRefresh(final ObjectName cmiOn) {
        String serverName = cmiOn.getKeyProperty("J2EEServer");
        ServerProxy proxy = getServerProxy(serverName);
        return ((Integer) proxy.getAttribute(cmiOn, "DelayToRefresh")).intValue();
    }

    /**
     * Set new value for the 'DelayToRefresh' attribute of a member's cmi MBean.
     * @param cmiOn CMI MBean's ObjectName
     * @param delayToRefresh new value to set
     */
    private void setDelayToRefresh(final ObjectName cmiOn, final int delayToRefresh) {
        String serverName = cmiOn.getKeyProperty("J2EEServer");
        ServerProxy proxy = getServerProxy(serverName);
        proxy.setAttribute(cmiOn, "DelayToRefresh", delayToRefresh);
    }
}
