/*-
 * ~~~~~~licensing~~~~~~
 * configuration-test-1
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.base.config;

import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationPlugin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(service = {ConfigurationPlugin.class, ImmutablesCollector.class}, immediate = true,
	property = {
			 ConfigurationPlugin.CM_RANKING + "=100"
			, "config.plugin.id=ImmutablesConfigurationPlugin"})
public class ImmutablesConfigurationPlugin implements ConfigurationPlugin, ImmutablesCollector {

	private static final Logger log = LoggerFactory.getLogger(ImmutablesConfigurationPlugin.class);
	
	protected BundleContext bundleContext;
	
	protected Map<String, Immutables> immutablesMap = new HashMap<>();
	
	protected Map<String, Dictionary<String, Object>> immutablesDataMap = new HashMap<>();
	
	@Reference(cardinality = ReferenceCardinality.MANDATORY)
	ConfigurationAdmin configurationAdmin;
	
	public void activate(ComponentContext componentContext) {
		this.bundleContext = componentContext.getBundleContext();
		log.debug("ImmutablesConfigurationPlugin activated");
	}
	
	@Override
	public void modifyConfiguration(ServiceReference<?> reference, Dictionary<String, Object> properties) {
		String pid = properties.get(Constants.SERVICE_PID).toString();
		if (immutablesDataMap.containsKey(pid)) {
			Dictionary<String, Object> ims = immutablesDataMap.get(pid);
			Iterator<String> iter = ims.keys().asIterator();
			while (iter.hasNext()) {
				String key = iter.next();
				properties.put(key, ims.get(key));
			}
			log.debug("DATA: " + pid + " FOUND");
		} else {
			log.debug("DATA: " + pid + " NOT FOUND");
		}
	}

	@Override
	public void add(Immutables immutables) {
		synchronized (immutablesDataMap) {
			boolean reload = true;
			if (immutablesDataMap.containsKey(immutables.getPid())) {
				Dictionary<String, Object> current = immutablesDataMap.get(immutables.getPid());
				reload = !immutables.getProperties().entrySet().stream()
					.allMatch(e -> e.getValue().equals(current.get(e.getKey())));
			}
			if (!reload) {
				log.debug("Immutables for " + immutables.getPid() + " already loaded");
				return;
			}
			immutablesDataMap.remove(immutables.getPid());
			log.debug("Adding direct Immutables for " + immutables.getPid());
			Dictionary<String, Object> ims = new Hashtable<>();
			Map<String, Object> properties = immutables.getProperties();
			if (properties != null)
				for (Entry<String, Object> entry: properties.entrySet())
					ims.put(entry.getKey(), entry.getValue());
			immutablesDataMap.put(immutables.getPid(), ims);
			try {
				Dictionary<String, Object> props = configurationAdmin.getConfiguration(immutables.getPid()).getProperties();
				if (props == null)
					props = new Hashtable<>();
				Iterator<String> keys = ims.keys().asIterator();
				while (keys.hasNext()) {
					String key = keys.next();
					props.put(key, ims.get(key));
				}
				configurationAdmin.getConfiguration(immutables.getPid()).setBundleLocation("?");
				configurationAdmin.getConfiguration(immutables.getPid()).update(props);
			} catch (IOException e) {
				log.error("Failed updateing configuration", e);
			}
		}
	}
}
