/*-
 * ~~~~~~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.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.apache.felix.utils.properties.TypedProperties;
import org.apache.karaf.config.core.ConfigRepository;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.base.support.CommonUtils;

public class DefaultPropertiesProvider implements Map<String, Object> {

	private static final Logger log = LoggerFactory.getLogger(DefaultPropertiesProvider.class);
	
	protected String objectId;
	
	protected String objectType;
	

	protected String configurationPid;
	protected BundleContext bundleContext;
	protected Map<String, Object> properties;

	public DefaultPropertiesProvider(String configurationPid
			, BundleContext bundleContext
			, Map<String, Object> properties) {
		
		this.configurationPid = configurationPid;
		this.bundleContext = bundleContext;
		this.properties = properties;
		register();
	}
	
	public DefaultPropertiesProvider(String objectId
			, String objectType
			, String configurationPid
			, BundleContext bundleContext
			, Map<String, Object> properties) {
		
		this.objectId = objectId;
		this.objectType = objectType;
		
		this.configurationPid = configurationPid;
		this.bundleContext = bundleContext;
		this.properties = properties;
		register();
	}

	protected void register() {
		if (!CommonUtils.isValid(objectId) || !CommonUtils.isValid(objectType))
			return;
		try {
			String fileName = System.getProperty("karaf.etc");
			Path path = Paths.get(fileName).resolve(objectType).resolve(configurationPid + ".cfg");

			File f = new File(path.toUri());
/*
			if ((this.configurationPid != null) && (this.bundleContext != null)) {
				
				ServiceReference<CustomConfigLocationCollector> collectorRef = 
						this.bundleContext.getServiceReference(CustomConfigLocationCollector.class);
				if (collectorRef != null) {
					CustomConfigLocationCollector collector = this.bundleContext.getService(collectorRef);
					if (collector != null)
						collector.addCustomLocation(configurationPid, "file:/" + f.getAbsolutePath().replace("\\", "/"));
					else
						log.error("registerImmutables :: COLLECTOR IS NULL");
					this.bundleContext.ungetService(collectorRef);
				} else {
					log.error("registerImmutables :: REF IS NULL");
				}
			}
*/			
			
			if (!f.exists()) {
				f.getParentFile().mkdirs();
				f.createNewFile();
			} else {
				// we're not updating existing files
				return;
			}
			
			ServiceReference<ConfigRepository> refCR = bundleContext.getServiceReference(ConfigRepository.class);
			if (refCR == null)
				return;
			ConfigRepository repo = bundleContext.getService(refCR);

			TypedProperties typedProperties;
			
/*			ServiceReference<ConfigurationAdmin> refCA = bundleContext.getServiceReference(ConfigurationAdmin.class);
			if (refCA == null)
				return;
			ConfigurationAdmin configAdmin = bundleContext.getService(refCA);
			Configuration config = configAdmin.getConfiguration(configurationPid);
			Dictionary<String, Object> props = config.getProperties();
			Iterator<String> iter = props.keys().asIterator(); 
			System.out.println("PROPS :: ");
			while(iter.hasNext()) {
				String key = iter.next();
				System.out.println(key + "-->" + props.get(key) + ":" + props.get(key).getClass().getName());
			}
			
			props.put("felix.fileinstall.filename", "file:/" + f.getAbsolutePath().replace("\\", "/"));
			config.update(props);
			
			TypedProperties typedProperties = repo.getConfig(configurationPid);

			System.out.println("TYPED PROPS 0:: ");
			for (Entry<String, Object> entry: typedProperties.entrySet())
				System.out.println(entry.getKey() + "-->" + entry.getValue() + ":" + entry.getValue().getClass().getName());
*/
			typedProperties = repo.getConfig(configurationPid);
			
			
			typedProperties.putAll(properties);
			typedProperties.remove( Constants.SERVICE_PID );
			typedProperties.remove( ConfigurationAdmin.SERVICE_FACTORYPID );
			typedProperties.remove( "felix.fileinstall.filename" );
			
			typedProperties.save(f);

//			typedProperties = repo.getConfig(configurationPid);
//			typedProperties.put("felix.fileinstall.filename", "file:/" + f.getAbsolutePath().replace("\\", "/"));
			
/*			repo.update(configurationPid, typedProperties);

			typedProperties = repo.getConfig(configurationPid);

			System.out.println("TYPED PROPS 2:: ");
			for (Entry<String, Object> entry: typedProperties.entrySet())
				System.out.println(entry.getKey() + "-->" + entry.getValue() + ":" + entry.getValue().getClass().getName());
*/			
			bundleContext.ungetService(refCR);
			
		} catch (IOException | InvalidSyntaxException  e) {
			log.error("Error registering default properties for " + configurationPid + "\n", e);
		}
		
	}
	
	@Override
	public int size() {
		return properties.size();
	}

	@Override
	public boolean isEmpty() {
		return properties.isEmpty();
	}

	@Override
	public boolean containsKey(Object key) {
		return properties.containsKey(key);
	}

	@Override
	public boolean containsValue(Object value) {
		return properties.containsValue(value);
	}

	@Override
	public Object get(Object key) {
		return properties.get(key);
	}

	@Override
	public Object put(String key, Object value) {
		return properties.put(key, value);
	}

	@Override
	public Object remove(Object key) {
		return properties.remove(key);
	}

	@Override
	public void putAll(Map<? extends String, ? extends Object> m) {
		properties.putAll(m);
	}

	@Override
	public void clear() {
		properties.clear();
	}

	@Override
	public Set<String> keySet() {
		return properties.keySet();
	}

	@Override
	public Collection<Object> values() {
		return properties.values();
	}

	@Override
	public Set<Entry<String, Object>> entrySet() {
		return properties.entrySet();
	}
	
}
