/*-
 * ~~~~~~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.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.management.NotCompliantMBeanException;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.platform.base.management.core.ManagementCore;
import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.core.producer.api.EntaxyProducer;
import ru.entaxy.platform.core.producer.management.FactoryMBean;
import ru.entaxy.platform.core.producer.management.ProducerMBean;

public class ProducerMBeanImpl extends AnnotatedMBean<ProducerMBean> 
		implements ProducerMBean, EntaxyProducer.EntaxyProducerListener {

	private static final Logger log = LoggerFactory.getLogger(ProducerMBeanImpl.class);
	
	protected BundleContext bundleContext;
	
	protected String managedType;
	protected EntaxyProducer entaxyProducer;
	
	protected Map<String, List<ServiceRegistration<FactoryMBean>>> services = new HashMap<>();
	protected Map<String, FactoryMBeanImpl> mbeans = new HashMap<>();
	
	public ProducerMBeanImpl(BundleContext bundleContext, String managedType, EntaxyProducer entaxyProducer) throws NotCompliantMBeanException {
		super(ProducerMBean.class);
		this.bundleContext = bundleContext;
		this.managedType = managedType;
		this.entaxyProducer = entaxyProducer;
		this.entaxyProducer.addListener(this);
		synchronized (this.services) {
			for(EntaxyFactory factory: this.entaxyProducer.getFactoriesForType(this.managedType))
				registerFactory(factory);
		}
	}

	@Override
	public void factoryAdded(String factoryId, String factoryType, EntaxyProducer producer) {
		if (!this.managedType.equals(factoryType))
			return;
		factoryRemoved(factoryId, factoryType, producer);
		synchronized (this.services) {
			registerFactory(this.entaxyProducer.getFactoryById(factoryId));
		}
	}

	@Override
	public void factoryRemoved(String factoryId, String factoryType, EntaxyProducer producer) {
		if (!this.managedType.equals(factoryType))
			return;
		synchronized (this.services) {
			if (this.services.containsKey(factoryId)) {
				for (ServiceRegistration<FactoryMBean> sr: this.services.get(factoryId))
					try {
						sr.unregister();
					} catch (Exception e) {
					}
				this.services.remove(factoryId);
				this.mbeans.remove(factoryId);
			}
		}
	}

	protected void registerFactory(EntaxyFactory factory) {
		try {
			FactoryMBeanImpl impl = new FactoryMBeanImpl(factory);
			
			Hashtable<String, String> props = new Hashtable<>();
			props.put(ManagementCore.JMX_OBJECTNAME
				, FactoryMBean.getQualifier(factory.getFactoryId(), factory.getFactoryType()).getValue());
			
			this.services.put(factory.getId()
					, FactoryMBeanPublisher.getInstance().publish(impl, factory));
			this.mbeans.put(factory.getId(), impl);
			
		} catch (NotCompliantMBeanException e) {
			log.error("Error creating FactoryMBeanImpl", e);
		}
	}
	
	public void beforeRemove() {
		synchronized (services) {
			for (List<ServiceRegistration<FactoryMBean>> lsr: services.values())
				for (ServiceRegistration<FactoryMBean> sr: lsr)
					try {
						sr.unregister();
					} catch (Exception e) {
						
					}
			services.clear();
			mbeans.clear();
		}
	}
	
}
