/*-
 * ~~~~~~licensing~~~~~~
 * connection-management
 * ==========
 * 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.core.management.connection.impl;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.management.DynamicMBean;
import javax.management.MBeanRegistration;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;

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 org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.ServiceScope;
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.Qualifier;
import ru.entaxy.esb.platform.core.management.connection.ConnectionMBean;
import ru.entaxy.esb.platform.core.management.connection.ConnectionsMBean;
import ru.entaxy.esb.platform.core.management.connection.tracker.DeployedConnectionTracker;

@Component(
		service = {ConnectionsMBean.class, DynamicMBean.class, MBeanRegistration.class},
		property = {ManagementCore.JMX_OBJECTNAME 
				+ "=" + ManagementCore.Q_RUNTIME_S  
				+ "," + ConnectionsMBean.CONNECTIONS_KEY
				+ "=" + ConnectionsMBean.CONNECTIONS_KEY_VALUE},
		scope = ServiceScope.SINGLETON,
		immediate = true		
		)
public class ConnectionsMBeanImpl extends StandardMBean 
		implements ConnectionsMBean, ManagedConnectionsListener {

	private static final Logger log = LoggerFactory.getLogger(ConnectionsMBeanImpl.class);
	
	public static final Qualifier Q_CONNECTIONS = ManagementCore.Q_RUNTIME
			.qualifier(ConnectionsMBean.CONNECTIONS_KEY, ConnectionsMBean.CONNECTIONS_KEY_VALUE); 
	
	protected BundleContext bundleContext;
	
	protected DeployedConnectionTracker tracker;
	
	protected static class ManagedConnectionDescriptor {
		
		ManagedConnection connection;
		ServiceRegistration<ConnectionMBean> registration;
		
	}
	
	protected Map<String, ManagedConnectionDescriptor> managed = new HashMap<>();
	
	public ConnectionsMBeanImpl() throws NotCompliantMBeanException {
		super(ConnectionsMBean.class);
	}
	
	@Activate
	public void activate(ComponentContext componentContext) {
		this.bundleContext = componentContext.getBundleContext();
		tracker = new DeployedConnectionTracker(bundleContext, this);
		tracker.open();
	}

	@Deactivate
	public void deactivate() {
		tracker.close();
	}
	
	@Override
	public void added(ManagedConnections connections) {
		Hashtable props = new Hashtable<>();
		// String jmxObjectName = "jmx.objectname";
		// String objectName = "ru.entaxy.esb:group=platform,category=connections,connection=";
		for (ManagedConnection connection: connections.managedConnections) {
			if (managed.containsKey(connection.getName()))
				this.managed.get(connection.getName()).registration.unregister();
			try {
				ConnectionMBeanImpl service = new ConnectionMBeanImpl(bundleContext, connection);
				ManagedConnectionDescriptor descriptor = new ManagedConnectionDescriptor();
				descriptor.connection = connection;
				props.put(ManagementCore.JMX_OBJECTNAME
						, Q_CONNECTIONS.qualifier(ConnectionMBean.CONNECTION_KEY
								, connection.getName()).getValue());
				descriptor.registration = bundleContext.registerService(ConnectionMBean.class
						, service
						, props);
				managed.put(connection.getName(), descriptor);
			} catch (Exception e) {
				log.error("Error adding connection [" + connection.getName() + "]", e);
			}
		}
	}
	
	@Override
	public void removed(ManagedConnections connections) {
		for (ManagedConnection connection: connections.managedConnections) {
			if (managed.containsKey(connection.getName())) {
				this.managed.get(connection.getName()).registration.unregister();
				this.managed.remove(connection.getName());
			}
		}
	}
}
