/*-
 * ~~~~~~licensing~~~~~~
 * object-producer-core
 * ==========
 * 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.IOException;
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.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension;
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionsAware;
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.wrapper.AbstractFactoryWrapper;
import ru.entaxy.platform.core.producer.wrapper.DefaultFactoryWrapper;

@Component(service = {EntaxyProducer.class}, immediate = true, name = "UniformExtendableProducer")
public class UniformExtendableProducer extends CommonObjectProducer implements EntaxyExtensionsAware {

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

    public static final String PRODUCER_EXTENSION_ATTR_SUPPORTED_TYPES = "supportedTypes";

    public static final String PRODUCER_EXTENSION_PATH = "producer";
    public static final String PRODUCER_EXTENSION_NAME = "config.json";

    public static final String PRODUCER_EXTENSION_KEY = PRODUCER_EXTENSION_PATH + "/" + PRODUCER_EXTENSION_NAME;

    protected Map<EntaxyExtension, List<String>> extensionsToSupportedTypesMap = new HashMap<>();

    protected Object extensionsLock = new Object();

    protected ComponentContext componentContext;

    protected List<EntaxyFactory> availableFactories = new ArrayList<>();

    protected Object factoriesLock = new Object();

    @Activate
    public void activate(ComponentContext componentContext) {
        this.componentContext = componentContext;
    }

    @Override
    public void addExtension(EntaxyExtension entaxyExtension) {
        if (!entaxyExtension.getResources().containsKey(PRODUCER_EXTENSION_KEY))
            return;

        synchronized (extensionsLock) {
            try {
                JsonObject config =
                        JSONUtils.getJsonRootObject(entaxyExtension.getResources().get(PRODUCER_EXTENSION_KEY));
                if (!config.has(PRODUCER_EXTENSION_ATTR_SUPPORTED_TYPES))
                    return;
                JsonArray ja = config.get(PRODUCER_EXTENSION_ATTR_SUPPORTED_TYPES).getAsJsonArray();
                if (ja.size() == 0)
                    return;
                final List<String> list = new ArrayList<>();
                for (int i = 0; i < ja.size(); i++) {
                    JsonElement je = ja.get(i);
                    if (!je.isJsonPrimitive())
                        continue;
                    if (!je.getAsJsonPrimitive().isString())
                        continue;
                    list.add(je.getAsJsonPrimitive().getAsString());
                }
                if (!list.isEmpty())
                    this.extensionsToSupportedTypesMap.put(entaxyExtension, list);
                calculateSupportedTypes();
                rescanAvailables();
            } catch (IOException e) {
                log.error(
                        "Error reading resource: [" + entaxyExtension.getResources().get(PRODUCER_EXTENSION_KEY) + "]",
                        e);
            }
        }
    }

    @Override
    public void removeExtension(EntaxyExtension entaxyExtension) {
        if (extensionsToSupportedTypesMap.containsKey(entaxyExtension)) {
            synchronized (extensionsLock) {
                extensionsToSupportedTypesMap.remove(entaxyExtension);
                calculateSupportedTypes();
                rescanExisting();
            }
        }

    }

    protected void rescanAvailables() {
        synchronized (factoriesLock) {
            for (EntaxyFactory factory : availableFactories)
                if (!factories.containsKey(factory))
                    addFactory(factory);
        }
    }

    protected void rescanExisting() {
        synchronized (factoriesLock) {
            List<EntaxyFactory> existing = new ArrayList<>(factories.values());
            for (EntaxyFactory factory : existing)
                if (!isTypeSupported(factory.getType()))
                    super.removeFactory(factory);
        }
    }

    protected void calculateSupportedTypes() {
        final List<String> typesList = new ArrayList<>();
        supportedTypes.clear();
        supportedTypesPatterns.clear();
        extensionsToSupportedTypesMap.values().stream()
                .forEach(list -> typesList.addAll(list));
        setSupportedTypes(typesList);
    }

    @Reference(bind = "addFactory", unbind = "removeFactory", cardinality = ReferenceCardinality.MULTIPLE,
            collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC,
            policyOption = ReferencePolicyOption.GREEDY)
    public void addFactory(EntaxyFactory factory) {
        synchronized (factoriesLock) {
            if (!availableFactories.contains(factory))
                availableFactories.add(factory);
        }
        doAddFactory(factory);
    }

    // WE MUST DECLARE IT for @Reference annotation processor
    @Override
    public void removeFactory(EntaxyFactory factory) {
        synchronized (factoriesLock) {
            availableFactories.remove(factory);
        }
        super.removeFactory(factory);

    }

    @Override
    protected AbstractFactoryWrapper doAddFactory(EntaxyFactory factory) {
        AbstractFactoryWrapper wrapper = super.doAddFactory(factory, DefaultFactoryWrapper.class);
        if (wrapper != null)
            wrapper.setGenerationProcessor(this);
        return wrapper;
    }

}
