/*-
 * ~~~~~~licensing~~~~~~
 * connection-manager
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed 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.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.platform.runtime.core.management.connection.util;

import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;

import ru.entaxy.esb.platform.runtime.core.management.connection.api.ConnectionManager;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;

public class ConnectionManagerUtil {
	
	private static ServiceTracker tracker = null;
	
    public static ConnectionManager getService() {
    	
    	// get our own bundleContext
        BundleContext bundleContext = FrameworkUtil.getBundle(ConnectionManagerUtil.class).getBundleContext();
        
        try {
			return OSGIUtils.services().bundleContext(bundleContext)
					.waitService(2000)
					.ofClass(ConnectionManager.class)
					.<ConnectionManager>get();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		}
        
        // found an issue: service is not returned 'cause the initializers start earlier than 
        // Karaf publishes service
        // So we should use tracker here to be sure the service is active
/*
        if (tracker == null) {
        	tracker = new ServiceTracker(bundleContext, ConnectionManager.class, null);
        	tracker.open();
        }
        try {
        	tracker.waitForService(2000);
        } catch (Exception e) {
			// TODO: handle exception
		}
*/        
/*        
        ServiceReference<ConnectionManager> connectionManagerServiceReference =
        		tracker.getServiceReference();
                // bundleContext.getServiceReference(ConnectionManager.class);
        return bundleContext.getService(connectionManagerServiceReference);
*/
    }
}
