/*-
 * ~~~~~~licensing~~~~~~
 * profile-commons
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.profile.commons.profile_output;

import org.apache.camel.Exchange;
import org.apache.camel.Header;
import org.apache.camel.ProducerTemplate;
import ru.entaxy.esb.system.common.exception.ConnectorNotFound;
import ru.entaxy.esb.system.common.osgi.impl.CommonNamedReferenceListener;
import ru.entaxy.esb.system.profile.commons.connectors.out.OutConnector;

public class ProfileOutputImpl extends CommonNamedReferenceListener<OutConnector> implements ProfileOutput {

    protected String systemName;

    public void setSystemName(String systemName) {
        this.systemName = systemName;
    }

    @Override
    public OutConnector getOutConnector(String endpointName) {
        if (endpointName == null || registeredReferences.get(endpointName) == null) {
            for (OutConnector outConnector : registeredReferences.values()) {
                return outConnector;
            }
        }
        return registeredReferences.get(endpointName);
    }

    @Override
    public void send(Exchange exchange) {
        ProducerTemplate template = exchange.getContext().createProducerTemplate();
        template.send("direct-vm:profile-" + systemName + "-enter-point?block=true&timeout=60000", exchange);
    }

    @Override
    public void sendTo(@Header("ENTAXY_EndpointName") String endpointName, Exchange exchange) {
        try {
            getOutConnector(endpointName).send(exchange);
        } catch (NullPointerException ex) {
            throw new ConnectorNotFound("Out connector for " + systemName + " not found");
        }
    }

    @Override
    protected String getObjectName(OutConnector outConnector) {
        return outConnector == null ? null : outConnector.getEndpointName();
    }
}
