/*-
 * ~~~~~~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.base.support.osgi.bundle;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import ru.entaxy.platform.base.support.CommonUtils;

public class CapabilityHelper {

    protected boolean isMultipleNamespacesSupported = false;

    protected Map<String, CapabilityDescriptorImpl> requiredCapabilities = new HashMap<>();
    protected Map<String, List<CapabilityDescriptorImpl>> providedCapabilities = new HashMap<>();
    
    protected Set<String> osgiCapabilities = new HashSet<>(); 

    public CapabilityHelper() {
        super();
        osgiCapabilities.add("osgi.identity");
        osgiCapabilities.add("osgi.wiring.bundle");
        osgiCapabilities.add("osgi.wiring.host");
    }

    protected void load() {
        /*
         * String existing =
         * this.manifest.getCustomAttributes().get(CapabilityDescriptor.HEADER_PROVIDE_CAPABILITY);
         * if (CommonUtils.isValid(existing)) { List<CapabilityDescriptorImpl> list =
         * parse(existing); for (CapabilityDescriptorImpl c: list) addProvidedCapability(c); }
         * existing =
         * this.manifest.getCustomAttributes().get(CapabilityDescriptor.HEADER_REQUIRE_CAPABILITY);
         * if (CommonUtils.isValid(existing)) { List<CapabilityDescriptorImpl> list =
         * parse(existing); for (CapabilityDescriptorImpl c: list) addRequiredCapability(c); }
         */
    }

    protected void addProvidedCapability(CapabilityDescriptorImpl capabilityDescriptorImpl) {
        if (capabilityDescriptorImpl == null)
            return;
        if (!isMultipleNamespacesSupported) {
            this.providedCapabilities.put(capabilityDescriptorImpl.getNamespace(),
                    Collections.singletonList(capabilityDescriptorImpl));
        } else {
            if (!this.providedCapabilities.containsKey(capabilityDescriptorImpl.getNamespace()))
                this.providedCapabilities.put(capabilityDescriptorImpl.getNamespace(), new ArrayList<>());
            this.providedCapabilities.get(capabilityDescriptorImpl.getNamespace())
                    .add(capabilityDescriptorImpl);
        }
    }



    protected void addRequiredCapability(CapabilityDescriptorImpl capabilityDescriptorImpl) {
        if (capabilityDescriptorImpl == null)
            return;
        this.requiredCapabilities.put(capabilityDescriptorImpl.getNamespace(), capabilityDescriptorImpl);
    }

    protected List<CapabilityDescriptorImpl> parse(String capabilities) {
        List<CapabilityDescriptorImpl> result = new ArrayList<>();
        String[] caps = capabilities.split(",");
        for (int i = 0; i < caps.length; i++)
            if (CommonUtils.isValid(caps[i])) {
                result.add(parseCapability(caps[i]));
            }
        return result;
    }

    protected CapabilityDescriptorImpl parseCapability(String capability) {
        String[] parsed = capability.split(";");
        CapabilityDescriptorImpl result = new CapabilityDescriptorImpl(parsed[0].trim());
        for (int i = 1; i < parsed.length; i++) {
            if (!CommonUtils.isValid(parsed[i]))
                continue;
            result.parseAttribute(parsed[i]);
        }
        return result;
    }

    public List<CapabilityDescriptor> getProvidedCapabilities() {
        return this.providedCapabilities.values().stream()
                .flatMap(List::stream)
                .map(c -> (CapabilityDescriptor) c)
                .collect(Collectors.toList());
    }
    
    public List<CapabilityDescriptor> getEntaxyObjectsProvidedCapabilities() {
        return this.providedCapabilities.entrySet().stream()
                .filter(e -> !osgiCapabilities.contains(e.getKey()))
                .map(e -> e.getValue())
                .flatMap(List::stream)
                .map(c -> (CapabilityDescriptor) c)
                .collect(Collectors.toList());
    }

    public List<CapabilityDescriptor> getProvidedCapabilities(String namespace) {
        if (!this.providedCapabilities.containsKey(namespace))
            return new ArrayList<>();
        return this.providedCapabilities.get(namespace)
                .stream()
                .map(c -> (CapabilityDescriptor) c)
                .collect(Collectors.toList());
    }


    public List<CapabilityDescriptor> getRequiredCapabilities() {
        return this.requiredCapabilities.values().stream()
                .map(c -> (CapabilityDescriptor) c)
                .collect(Collectors.toList());
    }

    public boolean isCapabilityProvided(String namespace) {
        return this.providedCapabilities.containsKey(namespace);
    }

    public boolean isCapabilityRequired(String namespace) {
        return this.requiredCapabilities.containsKey(namespace);
    }

    public CapabilityDescriptor provideCapability(String namespace) {
        CapabilityDescriptorImpl desc = new CapabilityDescriptorImpl(namespace);
        addProvidedCapability(desc);
        return desc;
    }

    public CapabilityDescriptor requireCapability(String namespace) {
        if (!this.requiredCapabilities.containsKey(namespace))
            this.requiredCapabilities.put(namespace, new CapabilityDescriptorImpl(namespace));
        return this.requiredCapabilities.get(namespace);
    }

    public boolean isMultipleNamespacesSupported() {
        return isMultipleNamespacesSupported;
    }

    public void setMultipleNamespacesSupported(boolean isMultipleNamespacesSupported) {
        this.isMultipleNamespacesSupported = isMultipleNamespacesSupported;
    }

}
