/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007-2009 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: ServiceTracker.java 17251 2009-04-29 11:30:58Z fornacif $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.service.manager;

import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.ow2.jonas.lib.management.javaee.J2EEServiceState;

/**
 * Treats OSGi ServiceEvents allowing to detect service state change.
 * @author Adriana.Danes@bull.net
 */
public class ServiceTracker implements ServiceListener {

    /**
     * Reference to the ServiceManagerImpl.
     */
    private ServiceManagerImpl serviceManager = null;

    /**
     * Create an OSGi Event Listener.
     * @param serviceManager Reference to the ServiceManager
     */
    public ServiceTracker(final ServiceManagerImpl serviceManager) {
        this.serviceManager = serviceManager;
    }

    /**
     * Track events concerning JOnAS services.
     * @param event received ServiceEvent
     */
    public void serviceChanged(final ServiceEvent event) {
        ServiceReference serviceReference = event.getServiceReference();
        String service = ServiceUtil.getJOnASService(serviceReference);
        if (service != null) {
            switch (event.getType()) {
                case ServiceEvent.REGISTERED:
                    serviceManager.setServiceState(service, J2EEServiceState.RUNNING);
                    synchronized (serviceManager) {
                        serviceManager.notify();
                    }
                    break;
                case ServiceEvent.MODIFIED:
                    break;
                case ServiceEvent.UNREGISTERING:
                    serviceManager.setServiceState(service, J2EEServiceState.STOPPED);
                    synchronized (serviceManager) {
                        serviceManager.notify();
                    }
                    break;
                default:
                    break;
            }
        }

    }


}
