/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * 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.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.CollectionType;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;

import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtendable;
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension;
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionsAware;
import ru.entaxy.esb.platform.runtime.base.extensions.api.Extendable;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.core.producer.api.EntaxyProducer;
import ru.entaxy.platform.core.producer.api.EntaxyProducerService;
import ru.entaxy.platform.core.producer.api.EntaxyProducerUtils;
import ru.entaxy.platform.core.producer.api.ProducerResult;
import ru.entaxy.platform.core.producer.api.ProducingCommandExecutor;
import ru.entaxy.platform.core.producer.executor.ProducingExecutor;
import ru.entaxy.platform.core.producer.executor.commands.Analyze;
import ru.entaxy.platform.core.producer.executor.commands.Build;
import ru.entaxy.platform.core.producer.executor.commands.Deploy;
import ru.entaxy.platform.core.producer.executor.commands.Enrich;
import ru.entaxy.platform.core.producer.executor.commands.Generate;
import ru.entaxy.platform.core.producer.executor.commands.Install;
import ru.entaxy.platform.core.producer.executor.commands.Layout;
import ru.entaxy.platform.core.producer.executor.commands.PrepareGenerate;
import ru.entaxy.platform.core.producer.executor.commands.Store;
import ru.entaxy.platform.core.producer.executor.commands.Validate;

@Component(service = {EntaxyProducerService.class, EntaxyExtendable.class}, immediate = true)
@Extendable("objectproducer")
public class EntaxyProducerServiceImpl implements EntaxyProducerService, EntaxyExtendable {

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

    private static final String LIFECYCLES_FILE_PATH = System.getProperty("karaf.etc")
            + File.separator
            + "producing.lifecycles.json";

    protected JsonObject lifecycles = new JsonObject();

    protected InstructionsHelper instructionsHelper;

    protected List<EntaxyProducer> producers = new ArrayList<>();

    protected Map<String, ProducingCommandExecutor> commandExecutors = new HashMap<>();

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

    protected Object lifecycleExtensionsLock = new Object();

    protected final List<EntaxyExtension> entaxyExtensions = new ArrayList<>();

    @Reference(bind = "addProducer", unbind = "removeProducer", cardinality = ReferenceCardinality.MULTIPLE,
            collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC,
            policyOption = ReferencePolicyOption.GREEDY)
    public void addProducer(EntaxyProducer producer) {
        producers.add(producer);
        if (producer instanceof EntaxyExtensionsAware)
            ((EntaxyExtensionsAware) producer).addExtensions(entaxyExtensions);
        log.debug("Producer added: " + producer.getProducerId());
    }

    public void removeProducer(EntaxyProducer producer) {
        producers.remove(producer);
        log.debug("Producer removed: " + producer.getProducerId());
    }

    @Activate
    public void activate(ComponentContext componentContext) {
        registerCommand(new Analyze(this));
        registerCommand(new Layout(this));
        registerCommand(new Validate(this));
        registerCommand(new PrepareGenerate(this));
        registerCommand(new Generate(this));
        registerCommand(new Build(this));
        registerCommand(new Deploy(this));
        registerCommand(new Install(this));
        registerCommand(new Enrich(this));
        registerCommand(new Store(this));
        initLifecycles();
    }

    protected void initLifecycles() {
        File lc = new File(LIFECYCLES_FILE_PATH);
        if (lc.exists() && lc.canRead()) {
            try {
                this.lifecycles = JSONUtils.getJsonRootObject(lc.toURI().toURL());
            } catch (Exception e) {
                log.warn("Error reading lifecycles config", e);
            }
        }
        this.instructionsHelper = new InstructionsHelper(this.lifecycles);
    }

    @Override
    public void registerCommand(ProducingCommandExecutor commandExecutor) {
        this.commandExecutors.put(commandExecutor.getId(), commandExecutor);
    }

    @Override
    public void extendLifecycle(String lifecycle, ProducingCommandExecutor commandExecutor,
            Map<String, Object> parameters) {
        synchronized (lifecycleExtensionsLock) {
            if (!lifecycleExtensions.containsKey(lifecycle))
                lifecycleExtensions.put(lifecycle, new HashMap<String, Map<String, Object>>());
            Map<String, Map<String, Object>> lifecycleExtension =
                    lifecycleExtensions.get(lifecycle);

            lifecycleExtension.put(commandExecutor.getId(), parameters);

            this.instructionsHelper.setLifecycleExtensions(lifecycleExtensions);
        }
    }

    @Override
    public ProducerResult produce(String configuration) {
        return this.produce(configuration, "{}");
    }

    @Override
    public ProducerResult produce(String configuration, String instructions) {
        return produce(JSONUtils.getJsonRootObject(configuration), instructions);
    }

    @Override
    public ProducerResult produce(JsonObject configuration) {
        return produce(configuration, "{}");
    }

    @Override
    public ProducerResult produce(JsonObject configuration, String instructions) {
        try {
            return (new ProducingExecutor(configuration, instructionsHelper.prepareInstructions(instructions), this))
                    .execute();
        } catch (Exception e) {
            log.error("Produce failed", e);
            return ProducerResult.createFailed(e);
        }
    }


    @Override
    public List<EntaxyProducer> getAllProducers() {
        return producers;
    }

    @Override
    public EntaxyProducer getProducerForType(String type) {
        List<EntaxyProducer> directSupport = new ArrayList<>();
        List<EntaxyProducer> patternSupport = new ArrayList<>();
        for (EntaxyProducer p : producers)
            for (String s : p.getSupportedTypes()) {
                if (EntaxyProducerUtils.isPattern(s)) {
                    if (EntaxyProducerUtils.isMatched(s, type))
                        patternSupport.add(p);
                } else if (s.equalsIgnoreCase(type))
                    directSupport.add(p);
            }
        if (!directSupport.isEmpty())
            return directSupport.get(0);
        if (!patternSupport.isEmpty())
            return patternSupport.get(0);
        return null;
    }

    @Override
    public List<ProducingCommandExecutor> getAvailableCommands() {
        return new ArrayList<>(commandExecutors.values());
    }

    @Override
    public ProducingCommandExecutor getCommandById(String id) {
        return this.commandExecutors.get(id);
    }

    @Override
    public EntaxyFactory findFactoryById(String factoryId) {
        for (EntaxyProducer p : getAllProducers()) {
            EntaxyFactory f = p.getFactoryById(factoryId);
            if (f != null)
                return f;
        }
        return null;
    }

    @Override
    public void addExtension(EntaxyExtension entaxyExtension) {
        if (!entaxyExtensions.contains(entaxyExtension)) {
            entaxyExtensions.add(entaxyExtension);
            producers.stream()
                    .filter(p -> (p instanceof EntaxyExtensionsAware))
                    .map(p -> (EntaxyExtensionsAware) p)
                    .forEach(p -> p.addExtension(entaxyExtension));
        }
    }

    @Override
    public void removeExtension(EntaxyExtension entaxyExtension) {
        entaxyExtensions.remove(entaxyExtension);
        producers.stream()
                .filter(p -> (p instanceof EntaxyExtensionsAware))
                .map(p -> (EntaxyExtensionsAware) p)
                .forEach(p -> p.removeExtension(entaxyExtension));
    }

    @Override
    public List<EntaxyExtension> getExtensions() {
        return entaxyExtensions;
    }
}
