/*-
 * ~~~~~~licensing~~~~~~
 * secure-vault-design
 * ==========
 * 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.security.vault.design.lookup;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.osgi.service.component.annotations.Activate;
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;

import com.google.gson.JsonObject;

import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.EntaxyObject.FIELDS;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory.OutputInfo;
import ru.entaxy.platform.base.objects.factory.exceptions.FactoryNotFoundException;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.core.producer.api.EntaxyProducerService;
import ru.entaxy.platform.core.producer.api.ExecutionPlan.ExecutionPlanUpdate;
import ru.entaxy.platform.core.producer.api.ProducerResult;
import ru.entaxy.platform.core.producer.api.ProducerResult.CommandResult;
import ru.entaxy.platform.core.producer.api.ProducingCommandExecutor;
import ru.entaxy.platform.core.producer.executor.AbstractCommandExecutor;
import ru.entaxy.platform.core.producer.executor.CommandExecutor;
import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObject;
import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectProxy;
import ru.entaxy.platform.core.producer.executor.objectmodel.ObjectModel;

@Component(service = ProducingCommandExecutor.class, immediate = true)
@CommandExecutor(id = "add-vaults-lookup", predecessors = {"add-config"}, descendants = {"process-resources"})
public class AddVaultsLookupCommand extends AbstractCommandExecutor implements ProducingCommandExecutor {

    private static final Logger LOG = LoggerFactory.getLogger(AddVaultsLookupCommand.class);

    public static final String SKIP_VAULTS_LOOKUP_DIRECTIVE = "@SKIP_VAULTS_LOOKUP";

    public static final String VAULTS_LOOKUP_FIELD = "##vaults";

    protected static final String VAULTS_FACTORY = "secure-vault-abstract";

    protected static final String VAULTS_OUTPUT_FIELD = "vaultsField";

    protected static final String VAULTS_OUTPUT_LOOKUP = "lookup";


    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    EntaxyProducerService entaxyProducerServiceLocal;

    Map<String, Object> vaultsFieldProperties = new HashMap<>();

    public AddVaultsLookupCommand() {
        super(null);
    }

    public AddVaultsLookupCommand(EntaxyProducerService entaxyProducerService) {
        super(entaxyProducerService);
    }

    @Activate
    public void activate() {
        this.entaxyProducerService = this.entaxyProducerServiceLocal;
        this.entaxyProducerService.registerCommand(this);
        this.entaxyProducerService.extendLifecycle("general", this, Collections.emptyMap());

        vaultsFieldProperties.put(EntaxyObject.FIELDS.FACTORY_ID, VAULTS_FACTORY);
        vaultsFieldProperties.put(EntaxyObject.FIELDS.OBJECT_ID, "vaultsLookup");
        vaultsFieldProperties.put(EntaxyObject.FIELDS.SCOPE, "private");
        vaultsFieldProperties.put("outputType", VAULTS_OUTPUT_FIELD);
        vaultsFieldProperties.put(EntaxyObject.FIELDS.PROPERTIES, Collections.emptyMap());

    }

    @Override
    protected boolean doExecute(ProducerResult currentResult, CommandResult commandResult,
            Map<String, Object> instructions) throws Exception {

        ObjectModel objectModel = currentResult.findResultObject(ObjectModel.class);
        objectModel.startTracking();

        JsonObject incomingJson = objectModel.getJsonCurrent().deepCopy();

        for (FactoredObject fo : objectModel.objects) {

            // skip proxies
            if (fo instanceof FactoredObjectProxy)
                continue;

            String factoryId = fo.factoryId;

            EntaxyFactory factory = entaxyProducerService.findFactoryById(factoryId);
            if (factory == null)
                throw new FactoryNotFoundException(factoryId);

            String output = fo.getOutputType();
            OutputInfo oi = CommonUtils.isValid(output) ? factory.getOutputByType(output) : factory.getDefaultOutput();
            Map<String, Object> config = oi.getConfig();
            if (config != null) {
                Object skipDirective = config.get(SKIP_VAULTS_LOOKUP_DIRECTIVE);
                if (skipDirective != null) {
                    LOG.debug("SKIPPING VAULTS LOOKUP FOR OBJECT :: {}/{}", fo.getObjectId(), fo.getObjectType());
                    continue;
                }
            }
            LOG.debug("OBJECT :: {}/{}", fo.getObjectId(), fo.getObjectType());

            if (!fo.getObjectType().startsWith("entaxy.runtime") || "entaxy.runtime.config".equals(fo.getObjectType()))
                continue;

            JsonObject objectOrigin = fo.origin;
            JsonObject objectProperties = objectOrigin.get(FIELDS.PROPERTIES).getAsJsonObject();

            if (objectProperties.has(VAULTS_LOOKUP_FIELD))
                continue;

            Generated g = entaxyProducerService.findFactoryById(VAULTS_FACTORY).generate(VAULTS_OUTPUT_FIELD, "private",
                    vaultsFieldProperties);

            objectProperties.add(VAULTS_LOOKUP_FIELD,
                    JSONUtils.getJsonRootObject(g.getObject().toString()));
            objectModel.setDirty();

        }

        if (objectModel.stopTracking()) {

            // remove ##embedded
            for (FactoredObject fo : objectModel.objects)
                fo.origin.remove(FactoredObject.EMBEDDED_FIELD);


            commandResult.planUpdate = ExecutionPlanUpdate.create()
                    // .updateInstructions().target("enrich").value("skip", true).complete()
                    .reset().target("analyze").complete();
        }

        JsonObject outgoingJson = objectModel.getJsonCurrent();

        printOutput("\n== INCOMING JSON ==\n");
        printOutput(incomingJson.toString());
        printOutput("\n== OUTGOING JSON ==\n");
        printOutput(outgoingJson.toString());

        commandResult.resultObject(outgoingJson);


        return true;
    }

}
