/*-
 * ~~~~~~licensing~~~~~~
 * config-plugin
 * ==========
 * 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.Dictionary;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationPlugin;
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;

/**
 * 
 * Configuration plugin providing resolving references from one config to others in a form
 * $PID_OF_OTHER_CONFIG{PROPERTY_NAME} e.g.
 * $org.ops4j.pax.url.mvn{org.ops4j.pax.url.mvn.localRepository}
 * 
 * If pid or property not found no changes are made
 * 
 * @author sstarovoytenkov
 *
 */
@Component(service = {ConfigurationPlugin.class}, immediate = true,
        property = {
            ConfigurationPlugin.CM_RANKING + "=100", "config.plugin.id=ConfigLookupConfigurationPlugin"})
public class ConfigLookupConfigurationPlugin implements ConfigurationPlugin {

    private static final Logger log = LoggerFactory.getLogger(ConfigLookupConfigurationPlugin.class);

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ConfigurationAdmin configurationAdmin;

    @Override
    public void modifyConfiguration(ServiceReference<?> arg0, Dictionary<String, Object> properties) {
        for (Enumeration<String> keys = properties.keys(); keys.hasMoreElements();) {
            String key = keys.nextElement();
            Object val = properties.get(key);
            if (val instanceof String) {

                String text = (String) val;
                String newValue = (String) val;
                Pattern pattern = Pattern.compile("\\$([^\\{\\}])+\\{.+?\\}");
                Matcher matcher = pattern.matcher(text);
                while (matcher.find()) {
                    log.debug("FOUND :: " + text.substring(matcher.start(), matcher.end()));
                    String placeholder = text.substring(matcher.start(), matcher.end());
                    String pid = placeholder.substring(1, placeholder.indexOf("{"));
                    String propName = placeholder.substring(placeholder.indexOf("{") + 1, placeholder.indexOf("}"));
                    log.debug("PARSED :: " + pid + ":" + propName);
                    Configuration conf;
                    try {
                        conf = configurationAdmin.getConfiguration(pid);
                        if (conf != null) {

                            Dictionary<String, Object> props = conf.getProperties();
                            if (props != null) {
                                Object value = props.get(propName);
                                log.debug("VALUE :: " + placeholder + " = " + value);
                                if (value != null) {
                                    newValue = newValue.replace(placeholder, (String) value);
                                    log.debug("NEW VALUE :: " + placeholder + " = " + newValue);
                                }
                            }

                        }
                    } catch (IOException e) {
                        log.error("Error with pid: " + pid, e);
                    }

                }

                properties.put(key, newValue);

            }
        }
    }

}
