/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.endpoint.collector.internal;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.ow2.jonas.endpoint.collector.Endpoint;
import org.ow2.jonas.endpoint.collector.IEndpoint;
import org.ow2.jonas.endpoint.collector.IEndpointBuilder;
import org.ow2.jonas.endpoint.collector.util.Util;
import org.ow2.jonas.jmx.JmxService;
import org.ow2.jonas.lib.service.AbsServiceImpl;
import org.ow2.jonas.service.ServiceException;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.relation.MBeanServerNotificationFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Represents an {@link IEndpoint} collector
 * @author Jeremy Cazaux
 */
public class EndpointCollector extends AbsServiceImpl implements NotificationListener {

    /**
     * The logger
     */
    private static Log logger = LogFactory.getLog(EndpointCollector.class);

    /**
     * Map between an {@link ObjectName} and its assocated {@link ServiceReference}
     */
    private Map<ObjectName, ServiceRegistration<IEndpoint>> endpointMap;

    /**
     * The {@link BundleContext}
     */
    private BundleContext bundleContext;

    /**
     * The {@link JmxService} 
     */
    private JmxService jmxService;

    /**
     * The {@link MBeanServer}
     */
    private MBeanServer mBeanServer;

    /**
     * The list of {@link IEndpointBuilder}
     */
    private List<IEndpointBuilder> endpointBuilders;

    /**
     * Default constructor
     */
    public EndpointCollector(final BundleContext bundleContext) {
        this.endpointMap = new HashMap<ObjectName, ServiceRegistration<IEndpoint>>();
        this.bundleContext = bundleContext;
        this.endpointBuilders = new ArrayList<IEndpointBuilder>();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doStart() throws ServiceException {
        MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter();
        filter.enableAllObjectNames();

        //add a notification listener on JMX connectors
        String jmxProtocolPattern = "connectors:protocol=rmi,name=*";
        ObjectName objectName = Util.getObjectName(jmxProtocolPattern);
        if (objectName != null) {
            Set<ObjectName> objectNameSet = this.mBeanServer.queryNames(objectName, null);
            for (ObjectName on: objectNameSet) {
                handleEndpoint(on);
            }
        }
        
        //add a notification listener on RMI connectors
        String rmiProtocolPattern = this.jmxService.getDomainName() + ":j2eeType=JNDIResource,name=*,J2EEServer=" +
                this.jmxService.getJonasServerName();
        objectName = Util.getObjectName(rmiProtocolPattern);
        if (objectName != null) {
            Set<ObjectName> objectNameSet = this.mBeanServer.queryNames(objectName, null);
            for (ObjectName on: objectNameSet) {
                handleEndpoint(on);
            }
        }
        
        //add a notification listener on the MBeanServerDelegate
        try {
            this.mBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this, filter, null);
        } catch (InstanceNotFoundException e) {
            logger.info("Cannot add notification listener on " + MBeanServerDelegate.DELEGATE_NAME, e);
        }     

        logger.info("Endpoint Collector started.");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doStop() throws ServiceException {
        try {
            this.mBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this);
        } catch (InstanceNotFoundException e) {
            logger.error("Cannot remove notification listener on " + MBeanServerDelegate.DELEGATE_NAME, e);
        } catch (ListenerNotFoundException e) {
            logger.error("Cannot remove notification listener on " + MBeanServerDelegate.DELEGATE_NAME, e);
        }
        logger.info("Endpoint Collector stopped.");
    }

    /**
     * @param jmxService The {@link org.ow2.jonas.jmx.JmxService} to bind
     */
    public void bindJmxService(final JmxService jmxService) {
        this.jmxService = jmxService;
        this.mBeanServer = jmxService.getJmxServer();
    }

    /**
     * @param jmxService The {@link JmxService} to unbind
     */
    public void unbindJmxService(final JmxService jmxService) {
        //this.mBeanServer = null;
    }

    /**
     * {@inheritDoc}
     */
    public void handleNotification(final Notification notification, final Object handback) {
        if (notification != null) {
            if (MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(notification.getType())) {
                MBeanServerNotification mBeanServerNotification = (MBeanServerNotification) notification;
                ObjectName objectName = mBeanServerNotification.getMBeanName();
                handleEndpoint(objectName);
            } else if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(notification.getType())) {
                MBeanServerNotification mBeanServerNotification = (MBeanServerNotification) notification;
                ObjectName objectName = mBeanServerNotification.getMBeanName();

                //unregister its associated endpoint
                ServiceRegistration serviceRegistration = this.endpointMap.get(objectName);
                if (serviceRegistration != null) {
                    serviceRegistration.unregister();
                }
            }
        }
    }

    /**
     * Register new Endpoint associated to the given {@link ObjectName} in the OSGi registry
     * @param objectName An {@link ObjectName}
     */
    private void handleEndpoint(final ObjectName objectName) {
        if (objectName != null) {
            IEndpoint endpoint = null;
            Pattern jmxPattern = Pattern.compile("connectors:protocol=rmi,name=.*");
            Pattern rmiPattern = Pattern.compile(".*:j2eeType=JNDIResource,name=.*,J2EEServer=.*");
            if (jmxPattern.matcher(objectName.toString()).matches()) {
                //handle JMX Endpoint
                endpoint = new Endpoint();
                Object value = getMBeanAttributeValue(objectName, "Address");
                if (value != null) {
                    endpoint.setUrl(String.valueOf(value));
                }  
                final String protocol = "jmx";
                endpoint.setProtocol(protocol);
                endpoint.setSource(IEndpoint.SOURCE_PREFIX + protocol);
            } else if (rmiPattern.matcher(objectName.toString()).matches()) {
                //handle RMI Endpoint
                endpoint = new Endpoint();
                Object value = getMBeanAttributeValue(objectName, "Name");
                if (value != null) {
                    String protocol = String.valueOf(value);
                    endpoint.setProtocol(protocol);
                    endpoint.setSource(IEndpoint.SOURCE_PREFIX + protocol);
                }
                value = getMBeanAttributeValue(objectName, "ProviderURL");
                if (value != null) {
                    endpoint.setUrl(String.valueOf(value));
                }
            } else {
                //handle other Endpoints
                IEndpointBuilder endpointBuilder = getEndpointBuilder(objectName);
                if (endpointBuilder != null) {
                    endpoint = endpointBuilder.buildEndpoint(objectName);
                }
            }

            if (endpoint != null) {
                //register the endpoint as an OSGi service
                this.endpointMap.put(objectName, (ServiceRegistration<IEndpoint>)
                        this.bundleContext.registerService(IEndpoint.class.getName(), endpoint, null));
            }
        }
    }

    /**
     * @param objectName The {@link ObjectName}
     * @param attribute An attribute of the associated MBean to retrieve
     * @return the value of the given attribute
     */
    public Object getMBeanAttributeValue(final ObjectName objectName, final String attribute) {
        return Util.getMBeanAttributeValue(objectName, attribute, this.mBeanServer);
    }

    /**
     * @param objectName The {@link ObjectName}
     * @return the first {@link IEndpointBuilder} which support the given {@link ObjectName}
     */
    private IEndpointBuilder getEndpointBuilder(final ObjectName objectName) {
        for (IEndpointBuilder endpointBuilder: this.endpointBuilders) {
            if (endpointBuilder.isSupport(objectName)) {
                return endpointBuilder;
            }
        }
        return null;
    }

    /**
     * @param endpointBuilder The {@link IEndpointBuilder} to bind
     */
    public void bindEndpointBuilder(final IEndpointBuilder endpointBuilder) {
        this.endpointBuilders.add(endpointBuilder);
    }

    /**
     * @param endpointBuilder The {@link IEndpointBuilder} to unbind
     */
    public void unbindEndpointBuilder(final IEndpointBuilder endpointBuilder) {
        //this.endpointBuilders.remove(endpointBuilder);
    }
}
