/*-
 * ~~~~~~licensing~~~~~~
 * object-producer-api
 * ==========
 * 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.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.support.JSONUtils;

public class EntaxyProducerUtils {

    protected static Gson sharedGson = new Gson();

    // INSTRUCTIONS BUILDER

    protected static class InstructionsItemBuilder {

        protected JsonObject instructionsJson;

        protected InstructionsItemBuilder(JsonObject jsonObject) {
            this.instructionsJson = jsonObject;
        }

    }

    public static class InstructionsBuilder extends InstructionsItemBuilder {

        protected InstructionsBuilder(JsonObject jsonObject) {
            super(jsonObject);
        }

        public InstructionsBuilder lifecycle(String lifecycle) {
            if (!instructionsJson.has(EntaxyProducerService.DIRECTIVES.LIFECYCLE))
                instructionsJson.add(EntaxyProducerService.DIRECTIVES.LIFECYCLE, new JsonArray());
            JsonArray lc = instructionsJson.get(EntaxyProducerService.DIRECTIVES.LIFECYCLE).getAsJsonArray();
            lc.add(lifecycle);
            return this;
        }

        public CommandBuilder command(String commandName) {
            if (!instructionsJson.has(commandName))
                instructionsJson.add(commandName, new JsonObject());
            if ("*".equals(commandName))
                return new AnyCommandBuilder(instructionsJson, instructionsJson.get(commandName).getAsJsonObject());
            else
                return new CommandBuilder(instructionsJson, instructionsJson.get(commandName).getAsJsonObject());

        }

        public AnyCommandBuilder any() {
            return (AnyCommandBuilder) this.command("*");
        }

        public JsonObject getInstructions() {
            return this.instructionsJson;
        }

        public String getInstructionsString() {
            return getInstructions().toString();
        }
    }

    public static class CommandBuilder extends InstructionsBuilder {

        protected JsonObject commandJson;

        protected CommandBuilder(JsonObject instructionsObject, JsonObject commandObject) {
            super(instructionsObject);
            commandJson = commandObject;
        }

        public CommandBuilder set(String name, Object value) {
            this.commandJson.remove(name);
            this.commandJson.add(name, sharedGson.toJsonTree(value));
            return this;
        }

    }

    public static class AnyCommandBuilder extends CommandBuilder {

        protected AnyCommandBuilder(JsonObject instructionsObject, JsonObject commandObject) {
            super(instructionsObject, commandObject);
        }

        public AnyCommandBuilder skip(String commandExprssion) {
            if (!this.commandJson.has(EntaxyProducerService.DIRECTIVES.SKIP))
                this.commandJson.add(EntaxyProducerService.DIRECTIVES.SKIP, new JsonArray());
            this.commandJson.get(EntaxyProducerService.DIRECTIVES.SKIP).getAsJsonArray().add(commandExprssion);
            return this;
        }

    }

    public static InstructionsBuilder instructions() {
        return instructions(new JsonObject());
    }

    public static InstructionsBuilder instructions(JsonObject jsonObject) {
        return new InstructionsBuilder(jsonObject);
    }

    // CONFIGURATION BUILDER


    // UTILS

    public static boolean isPattern(String type) {
        return type.contains(EntaxyProducer.PATTERN_CHAR_ANY);
    }

    public static String toRegexPattern(String type) {
        return type.replaceAll("\\.", "\\\\.")
                .replaceAll("\\" + EntaxyProducer.PATTERN_CHAR_ANY, "\\.*");
    }

    public static boolean isMatched(String typePattern, String type) {
        return Pattern.matches(toRegexPattern(typePattern), type);
    }

    public static Map<String, Object> getFactoryEssence(EntaxyFactory factory) {
        return getFactoryEssence(factory, "");
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> getFactoryEssence(EntaxyFactory factory, String prefix) {
        Map<String, Object> result = new LinkedHashMap<>();
        JsonObject config = JSONUtils.getJsonRootObject(factory.getJsonConfiguration());

        if (config == null)
            return result;

        if (!config.has(EntaxyFactory.CONFIGURATION.FACTORY_SECTION_NAME))
            return result;

        Object obj = JSONUtils.element2object(config.get(EntaxyFactory.CONFIGURATION.FACTORY_SECTION_NAME));

        if (!(obj instanceof Map))
            return result;

        result.putAll((Map<String, Object>) ((Map<String, Object>) obj).entrySet().stream()
                .collect(() -> new LinkedHashMap<String, Object>(),
                        (m, e) -> m.put(String.format("%s%s", prefix, e.getKey()), e.getValue()), HashMap::putAll));

        result.putAll(factory.getTypeInfo().entrySet().stream()
                .collect(() -> new LinkedHashMap<String, Object>(),
                        (m, e) -> m.put(String.format("%stypeinfo.%s", prefix, e.getKey()), e.getValue()),
                        HashMap::putAll)

        );

        return result;
    }

    public static boolean factoryMatches(String filter, EntaxyFactory factory) {
        try {
            return factoryMatchesUnsafe(filter, factory);
        } catch (InvalidSyntaxException ignore) {
            return false;
        }
    }

    public static boolean factoryMatchesUnsafe(String filter, EntaxyFactory factory) throws InvalidSyntaxException {
        return factoryMatches(FrameworkUtil.createFilter(filter), factory);
    }

    public static boolean factoryMatches(Filter filter, EntaxyFactory factory) {
        return filter.matches(getFactoryEssence(factory));
    }

    public static List<EntaxyFactory> filterFactories(String filter, List<EntaxyFactory> factories) {
        try {
            return filterFactoriesUnsafe(filter, factories);
        } catch (InvalidSyntaxException ignore) {
            return new ArrayList<>();
        }
    }

    public static List<EntaxyFactory> filterFactoriesUnsafe(String filter, List<EntaxyFactory> factories)
            throws InvalidSyntaxException {
        Filter osgiFilter = FrameworkUtil.createFilter(filter);

        return filterFactories(osgiFilter, factories);

    }

    public static List<EntaxyFactory> filterFactories(Filter filter, List<EntaxyFactory> factories) {
        return factories.stream().filter(f -> factoryMatches(filter, f)).collect(Collectors.toList());
    }
}
