/*-
 * ~~~~~~licensing~~~~~~
 * resources-service
 * ==========
 * 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.esb.resources.impl.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.esb.resources.EntaxyResourceProviderProxy;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.esb.resources.EntaxyResourceService.EntaxyResourceProtocolAvailableCallback;

public class ProvidersController {

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

    protected BundleContext bundleContext;

    protected EntaxyResourceService resourceService;

    protected Map<String, EntaxyResourceProvider> providers = new ConcurrentHashMap<>();

    protected Object providersLock = new Object();

    protected Map<String, ProxyController> proxies = new ConcurrentHashMap<>();

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

    protected Map<String, List<EntaxyResourceProtocolAvailableCallback>> callbacks =
            new ConcurrentHashMap<String, List<EntaxyResourceProtocolAvailableCallback>>();

    public ProvidersController(BundleContext bundleContext, EntaxyResourceService resourceService) {
        super();
        this.bundleContext = bundleContext;
        this.resourceService = resourceService;
    }

    public boolean hasProvider(String protocol) {
        return this.providers.containsKey(protocol);
    }

    public EntaxyResourceProvider getProvider(String protocol) {
        return this.providers.getOrDefault(protocol, null);
    }

    public Map<String, EntaxyResourceProvider> getProviders() {
        return this.providers;
    }

    public void registerProtocolCallback(String protocol, EntaxyResourceProtocolAvailableCallback callback) {
        if (!callbacks.containsKey(protocol))
            callbacks.put(protocol, new ArrayList<>());

        synchronized (providersLock) {
            if (hasProvider(protocol))
                callback.protocolAvailable();
            else
                callbacks.get(protocol).add(callback);
        }
    }

    public void addProvider(EntaxyResourceProvider provider) {
        synchronized (providersLock) {
            this.providers.put(provider.getProtocol(), provider);
        }
        if (callbacks.containsKey(provider.getProtocol())) {
            for (EntaxyResourceProtocolAvailableCallback callback : callbacks.get(provider.getProtocol()))
                callback.protocolAvailable();
            callbacks.remove(provider.getProtocol());
        }
        log.info("RESOURCE PROVIDER ADDED: " + provider.getProtocol());
        activateCascadeFrom(provider.getProtocol());
    }

    public void removeProvider(EntaxyResourceProvider provider) {
        deactivateCascadeFrom(provider.getProtocol());
        this.providers.remove(provider.getProtocol());
    }

    public void addProxy(EntaxyResourceProviderProxy proxy) {
        this.proxies.put(proxy.getProtocol(), new ProxyController(bundleContext, proxy, resourceService));
        addDependency(proxy.getTargetProtocol(), proxy.getProtocol());
        if (isDependenciesSatisfied(proxy.getProtocol()))
            activateProxy(proxy.getProtocol());
    }

    public void removeProxy(EntaxyResourceProviderProxy proxy) {
        this.proxies.remove(proxy.getProtocol());
    }

    protected void addDependency(String target, String proxy) {
        this.dependencies.put(proxy, target);
    }

    protected boolean isDependenciesSatisfied(String proxy) {
        if (!this.dependencies.containsKey(proxy))
            return true;
        return this.hasProvider(this.dependencies.get(proxy));
    }

    protected void activateCascadeFrom(String protocol) {
        for (String proxy : getDependentsFor(protocol)) {
            if (this.proxies.containsKey(proxy))
                this.proxies.get(proxy).activate();
        }
    }

    protected void deactivateCascadeFrom(String protocol) {
        for (String proxy : getDependentsFor(protocol)) {
            if (this.proxies.containsKey(proxy))
                this.proxies.get(proxy).deactivate();
        }
    }

    protected List<String> getDependentsFor(String target) {
        return this.dependencies.entrySet().stream()
                .filter(e -> e.getValue().equals(target))
                .map(e -> e.getKey())
                .collect(Collectors.toList());
    }

    protected void activateProxy(String proxy) {
        if (this.proxies.containsKey(proxy))
            this.proxies.get(proxy).activate();
    }

    protected void deactivateProxy(String proxy) {
        if (this.proxies.containsKey(proxy))
            this.proxies.get(proxy).deactivate();
    }

}
