/*-
 * ~~~~~~licensing~~~~~~
 * system-component
 * ==========
 * 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.system.component;

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.support.DefaultProducer;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.system.common.exception.ProfileNotFound;
import ru.entaxy.esb.system.registry.systems.profile.SystemCollectorListener;
import ru.entaxy.esb.system.registry.systems.profile.SystemProfile;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;


public class SystemProducer extends DefaultProducer {

    private static final Logger LOG = LoggerFactory.getLogger(SystemProducer.class);
    private final SystemEndpoint endpoint;

    private SystemCollectorListener systemCollectorListener;

    public SystemProducer(SystemEndpoint endpoint) {
        super(endpoint);
        this.endpoint = endpoint;
    }

    public void process(Exchange exchange) throws Exception {
        LOG.debug("In SystemProducer " + exchange.getIn().getBody());

        // get System Profile from systemRegistry endpoint.getSystemName()
        SystemProfile systemProfile = null;

        systemProfile = getSystemProfile(endpoint.getSystemName());

        setPreferredConnector(exchange);
        setConnectorMandatory(exchange);

        LOG.debug("Called system profile " + (systemProfile != null ? systemProfile.getSystemName() : "NULL"));

        systemProfile.send(exchange);

    }

    public SystemProfile getSystemProfile(String nameSystem) throws ProfileNotFound {
        systemCollectorListener = getSystemProfileNamedListener();
        LOG.debug("Registry SystemProfile {}; systems count {}", nameSystem,
                systemCollectorListener.getReferenceNames().size());
        SystemProfile systemProfile = null;
        if (systemCollectorListener.isRegistered(nameSystem)) {
            systemProfile = (SystemProfile) systemCollectorListener.getReference(nameSystem);
        } else {
            throw new ProfileNotFound("Profile for system " + nameSystem + " not found");
        }
        return systemProfile;
    }

    public SystemCollectorListener getSystemProfileNamedListener() {
        if (systemCollectorListener == null) {
            systemCollectorListener = (SystemCollectorListener) OSGIUtils.getService(
                    FrameworkUtil.getBundle(SystemProducer.class).getBundleContext(),
                    SystemCollectorListener.class);
        }
        return systemCollectorListener;
    }

    public void setPreferredConnector(Exchange exchange) {
        if (!StringUtils.isEmpty(endpoint.getConnectorProtocol())
                || !StringUtils.isEmpty(endpoint.getConnectorClassifier()) ||
                !StringUtils.isEmpty(endpoint.getConnectorType())) {
            List<String> preferredConnectorList = new ArrayList<>();
            if (!StringUtils.isEmpty(endpoint.getConnectorProtocol())) {
                preferredConnectorList.add("\"protocol\":\"" + endpoint.getConnectorProtocol() + "\"");
            }
            if (!StringUtils.isEmpty(endpoint.getConnectorClassifier())) {
                preferredConnectorList.add("\"classifier\":\"" + endpoint.getConnectorClassifier() + "\"");
            }
            if (!StringUtils.isEmpty(endpoint.getConnectorType())) {
                preferredConnectorList.add("\"type\":\"" + endpoint.getConnectorType() + "\"");
            }
            String jsonPreferredConnector = "{" + joinByComma(preferredConnectorList) + "}";
            exchange.getMessage().getHeaders().put("NTX_preferred_connector", jsonPreferredConnector);
        }
    }

    public void setConnectorMandatory(Exchange exchange) {
        if (endpoint.isConnectorMandatory() != null)
            exchange.getMessage().getHeaders().put("NTX_connector_preferred_as_mandatory",
                    endpoint.isConnectorMandatory());
    }

    private String joinByComma(List<String> preferredConnectorList) {
        StringBuilder summary = new StringBuilder();
        for (int i = 0; i < preferredConnectorList.size(); i++) {
            summary.append(preferredConnectorList.get(i));
            if (i < preferredConnectorList.size() - 1) {
                summary.append(",");
            }
        }
        return summary.toString();
    }
}
