/*-
 * ~~~~~~licensing~~~~~~
 * profile-management
 * ==========
 * 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.management.profile.support.legacy;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.wiring.BundleCapability;

import ru.entaxy.esb.platform.base.management.core.utils.ExtendedBundleTrackerCustomizer;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.osgi.tracker.filter.BundleCapabilityFilter;

public class DeployedLegacyConnectorCustomizer extends ExtendedBundleTrackerCustomizer<List<ManagedLegacyConnector>> {

    @Override
    protected List<ManagedLegacyConnector> createManagedObject(Bundle bundle, BundleEvent event,
            Map<String, List<?>> filterResults) {
        @SuppressWarnings("unchecked")
        List<BundleCapability> capabilities =
                (List<BundleCapability>) filterResults.get(BundleCapabilityFilter.DEFAULT_FILTER_ID);
        if (capabilities == null)
            capabilities = new ArrayList<>();
        List<ManagedLegacyConnector> result = new ArrayList<>();


        for (BundleCapability capability : capabilities) {

            // process only legacy connectors
            if (capability.getAttributes().containsKey("objectId")
                    && capability.getAttributes().containsKey("factory")) {
                // it's factory-based connector
                continue;
            }


            Object val = capability.getAttributes().get("name");
            String name = val == null ? "" : val.toString();
            if (!CommonUtils.isValid(name))
                continue;
            val = capability.getAttributes().get("system");
            String system = val == null ? "" : val.toString();
            if (!CommonUtils.isValid(system))
                continue;

            val = capability.getAttributes().get("templateId");
            String factoryId = val == null ? "" : val.toString();

            val = capability.getAttributes().get("factory");
            factoryId = val == null ? factoryId : val.toString();

            val = capability.getAttributes().get("bundleName");
            String registeredName = val == null ? "" : val.toString();

            val = capability.getAttributes().get("classifier");
            String classifier = val == null ? "" : val.toString();

            val = capability.getAttributes().get("displayName");
            String displayName;
            try {
                displayName =
                        val == null ? "" : new String(val.toString().getBytes(StandardCharsets.ISO_8859_1), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                displayName = val == null ? "" : val.toString();
            }

            val = capability.getAttributes().get("direction");
            String direction = val == null ? "" : val.toString();


            ManagedLegacyConnector mc = (new ManagedLegacyConnector())
                    .name(name)
                    .system(system)
                    .factoryId(factoryId)
                    .registeredName(registeredName)
                    .classifier(classifier)
                    .displayName(displayName)
                    .direction(direction);
            enrich(bundle, event, filterResults, mc);
            result.add(mc);
        }
        return result;
    }

}
