/*-
 * ~~~~~~licensing~~~~~~
 * object-producing-config-support
 * ==========
 * 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.core.producer.config.support;

import java.util.Map;

import org.apache.felix.utils.properties.TypedProperties;
import org.apache.karaf.config.core.ConfigRepository;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.annotations.Component;

import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.platform.config.runtime.ObjectConfigHelper;
import ru.entaxy.platform.core.producer.executor.builder.BuiltObject;
import ru.entaxy.platform.core.producer.executor.builder.DefaultBuiltObject;
import ru.entaxy.platform.core.producer.executor.builder.ObjectBuilder;
import ru.entaxy.platform.core.producer.executor.deployer.DefaultDeployedObject;
import ru.entaxy.platform.core.producer.executor.deployer.DeployedObject;
import ru.entaxy.platform.core.producer.executor.deployer.ObjectDeployer;
import ru.entaxy.platform.core.producer.executor.installer.DefaultInstalledObject;
import ru.entaxy.platform.core.producer.executor.installer.InstalledObject;
import ru.entaxy.platform.core.producer.executor.installer.ObjectInstaller;

@Component(service = {ObjectBuilder.class, ObjectDeployer.class, ObjectInstaller.class})
public class ConfigObjectSupport implements ObjectBuilder, ObjectDeployer, ObjectInstaller {

    private static final String CONFIG_TYPE_PREFIX = "config:";

    @Override
    public boolean isBuildable(Generated generated) {
        return generated.getType().startsWith(CONFIG_TYPE_PREFIX);
    }

    @Override
    public BuiltObject build(Generated generated, Map<String, Object> instructions) throws Exception {
        return new DefaultBuiltObject(new DeployableConfig(
                generated.getProperties().getOrDefault("configurationPid",
                        generated.getProperties().getOrDefault("objectId", "unknown")).toString(),

                generated.getObject().toString()));
    }

    @Override
    public boolean isDeployable(BuiltObject object) {
        return object.getObject() instanceof DeployableConfig;
    }

    @Override
    public DeployedObject deploy(BuiltObject object, Map<String, Object> instructions) throws Exception {
        return new DefaultDeployedObject(object.getObject());
    }

    @Override
    public boolean isInstallable(DeployedObject object) {
        return object.getObject() instanceof DeployableConfig;
    }

    @Override
    public InstalledObject install(DeployedObject object, Map<String, Object> instructions) throws Exception {
        DeployableConfig deployableConfig = (DeployableConfig) object.getObject();
        Map<String, Object> map = deployableConfig.properties;

        ServiceReference<ConfigRepository> ref = ObjectConfigHelper.getInstance().getReference(ConfigRepository.class);
        ServiceReference<ConfigurationAdmin> ref2 =
                ObjectConfigHelper.getInstance().getReference(ConfigurationAdmin.class);
        if (ref != null) {

            ConfigurationAdmin configurationAdmin = ObjectConfigHelper.getInstance().getService(ref2);

            // we need this to not bind config to felix bundle
            configurationAdmin.getConfiguration(deployableConfig.configurationPid, "?");

            ConfigRepository configRepository = ObjectConfigHelper.getInstance().getService(ref);
            TypedProperties typedProperties = configRepository.getConfig(deployableConfig.configurationPid);

            typedProperties.clear();

            for (Map.Entry<String, Object> entry : map.entrySet())
                typedProperties.put(entry.getKey(), entry.getValue());

            configRepository.update(deployableConfig.configurationPid, typedProperties);

            ObjectConfigHelper.getInstance().ungetService(ref);
            ObjectConfigHelper.getInstance().ungetService(ref2);
        }

        return new DefaultInstalledObject(map);
    }

}
