/*
 * Copyright 2010-2013 Ning, Inc.
 *
 * Ning licenses this file to you under the Apache License, version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License.  You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.ning.billing.osgi.bundles.logger;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogListener;
import org.osgi.service.log.LogReaderService;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Activator implements BundleActivator {

    private static final Logger logger = LoggerFactory.getLogger(Activator.class);

    private final LogListener killbillLogListener = new KillbillLogWriter();
    private final List<LogReaderService> logReaderServices = new LinkedList<LogReaderService>();

    private final ServiceListener logReaderServiceListener = new ServiceListener() {
        public void serviceChanged(final ServiceEvent event) {
            final ServiceReference serviceReference = event.getServiceReference();
            if (serviceReference == null || serviceReference.getBundle() == null) {
                return;
            }

            final BundleContext bundleContext = serviceReference.getBundle().getBundleContext();
            if (bundleContext == null) {
                return;
            }

            final LogReaderService logReaderService = (LogReaderService) bundleContext.getService(serviceReference);
            if (logReaderService != null) {
                if (event.getType() == ServiceEvent.REGISTERED) {
                    registerLogReaderService(logReaderService);
                } else if (event.getType() == ServiceEvent.UNREGISTERING) {
                    logReaderService.removeLogListener(killbillLogListener);
                    logReaderServices.remove(logReaderService);
                }
            }
        }
    };

    @Override
    public void start(final BundleContext context) throws Exception {
        // Get a list of all the registered LogReaderService, and add the killbill listener
        final ServiceTracker logReaderTracker = new ServiceTracker(context, LogReaderService.class.getName(), null);
        logReaderTracker.open();
        final Object[] readers = logReaderTracker.getServices();
        if (readers != null) {
            for (final Object reader : readers) {
                final LogReaderService service = (LogReaderService) reader;
                registerLogReaderService(service);
            }
        }
        logReaderTracker.close();

        // Add the ServiceListener
        final String filter = "(objectclass=" + LogReaderService.class.getName() + ")";
        try {
            context.addServiceListener(logReaderServiceListener, filter);
        } catch (InvalidSyntaxException e) {
            logger.warn("Unable to register the killbill LogReaderService listener", e);
        }
    }

    @Override
    public void stop(final BundleContext context) throws Exception {
        for (final Iterator<LogReaderService> iterator = logReaderServices.iterator(); iterator.hasNext(); ) {
            final LogReaderService service = iterator.next();
            service.removeLogListener(killbillLogListener);
            iterator.remove();
        }
    }

    private void registerLogReaderService(final LogReaderService service) {
        logReaderServices.add(service);
        service.addLogListener(killbillLogListener);
    }
}

@@ -1096,53 +1096,8 @@
 ce;%0A
-import org.osgi.util.tracker.ServiceTracker;%0A
 impo
@@ -2384,86 +2384,19 @@
     
-logReaderService.removeLogListener(killbillLogListener);%0A                    l
+unregisterL
 ogRe
@@ -2410,16 +2410,8 @@
 vice
-s.remove
 (log
@@ -2564,617 +2564,8 @@
 n %7B%0A
-        // Get a list of all the registered LogReaderService, and add the killbill listener%0A        final ServiceTracker logReaderTracker = new ServiceTracker(context, LogReaderService.class.getName(), null);%0A        logReaderTracker.open();%0A        final Object%5B%5D readers = logReaderTracker.getServices();%0A        if (readers != null) %7B%0A            for (final Object reader : readers) %7B%0A                final LogReaderService service = (LogReaderService) reader;%0A                registerLogReaderService(service);%0A            %7D%0A        %7D%0A        logReaderTracker.close();%0A%0A        // Add the ServiceListener%0A
     
@@ -2753,16 +2753,22 @@
  catch (
+final 
 InvalidS
@@ -2877,32 +2877,461 @@
 %22, e);%0A        %7D
+%0A%0A        // If the LogReaderService was already registered, manually construct a REGISTERED ServiceEvent%0A        final ServiceReference%5B%5D serviceReferences = context.getServiceReferences((String) null, filter);%0A        for (int i = 0; serviceReferences != null && i %3C serviceReferences.length; i++) %7B%0A            logReaderServiceListener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, serviceReferences%5Bi%5D));%0A        %7D
 %0A    %7D%0A%0A    @Ove
@@ -3758,24 +3758,99 @@
  service) %7B%0A
+        logger.info(%22Registering the killbill LogReaderService listener%22);%0A
         logR
@@ -3935,11 +3935,299 @@
 );%0A    %7D
+%0A%0A    private void unregisterLogReaderService(final LogReaderService logReaderService) %7B%0A        logger.info(%22Unregistering the killbill LogReaderService listener%22);%0A        logReaderService.removeLogListener(killbillLogListener);%0A        logReaderServices.remove(logReaderService);%0A    %7D
 %0A%7D%0A

fix bug in logger bundle registration process