/*-
 * ~~~~~~licensing~~~~~~
 * object-producing-management
 * ==========
 * Copyright (C) 2020 - 2022 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.platform.core.producer.management.impl;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;

import ru.entaxy.esb.platform.base.management.core.ManagementCore;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.core.producer.management.FactoryMBean;

@Component(service = FactoryMBeanPublisher.class, immediate = true)
public class FactoryMBeanPublisher {

	protected static FactoryMBeanPublisher _INSTANCE = null;
	
	public static FactoryMBeanPublisher getInstance() {
		return _INSTANCE;
	};
	
	protected BundleContext bundleContext;
	
	@Activate
	public void activate(ComponentContext componentContext) {
		this.bundleContext = componentContext.getBundleContext();
		_INSTANCE = this;
	}
	
	public List<ServiceRegistration<FactoryMBean>> publish(FactoryMBeanImpl service, EntaxyFactory factory){
		
		List<ServiceRegistration<FactoryMBean>> result = new ArrayList<>();
		
		Hashtable<String, String> props = new Hashtable<>();
		props.put(ManagementCore.JMX_OBJECTNAME
			, FactoryMBean.getQualifier(factory.getId(), factory.getType()).getValue());
		
		result.add(this.bundleContext.registerService(FactoryMBean.class, service, props));
		
		if (CommonUtils.isValid(factory.getCategory())) {
			props.put(ManagementCore.JMX_OBJECTNAME
					, ManagementCore.Q_PLATFORM
						.qualifier(FactoryMBean.CATEGORY_KEY, factory.getCategory())
						.qualifier(FactoryMBean.FACTORY_KEY, factory.getId()).getValue());
			
			result.add(this.bundleContext.registerService(FactoryMBean.class, service, props));
			
		}
		
		return result;
		
	}
	
}
