/*-
 * ~~~~~~licensing~~~~~~
 * profile-commons
 * ==========
 * 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.profile.commons.profile_output;

import static ru.entaxy.esb.system.profile.commons.connectors.Connector.HEADERS_START;
import static ru.entaxy.esb.system.profile.commons.connectors.Connector.ROLE;
import static ru.entaxy.esb.system.profile.commons.connectors.Connector.SUBTYPE;
import static ru.entaxy.esb.system.profile.commons.connectors.Connector.TYPE;

import java.util.concurrent.CountDownLatch;

import org.apache.camel.Exchange;
import org.apache.camel.Header;
import org.apache.camel.ProducerTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.system.common.exception.ConnectorNotFound;
import ru.entaxy.esb.system.profile.commons.connectors.out.OutConnector;
import ru.entaxy.platform.base.support.osgi.service.CommonNamedReferenceListener;

public class ProfileOutputImpl extends CommonNamedReferenceListener<OutConnector> implements ProfileOutput {

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

    protected String systemName;

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

    @Override
    public OutConnector getOutConnector(String endpointName, String role, String type, String subtype) {
        for (OutConnector outConnector : registeredReferences.values()) {
            if ((role == null || role.equals(outConnector.getParam(ROLE))) &&
                    type != null && type.equals(outConnector.getParam(TYPE)) &&
                    subtype != null && subtype.equals(outConnector.getParam(SUBTYPE))) {
                return outConnector;
            } else if ((role == null || role.equals(outConnector.getParam(ROLE))) &&
                    type != null && type.equals(outConnector.getParam(TYPE))) {
                return outConnector;
            } else if (role != null && role.equals(outConnector.getParam(ROLE))) {
                return outConnector;
            }
        }
        if (endpointName == null || registeredReferences.get(endpointName) == null) {
            for (OutConnector outConnector : registeredReferences.values()) {
                return outConnector;
            }
        }
        return registeredReferences.get(endpointName);
    }

    @Override
    public void send(Exchange exchange) {
        /*
         * !!! WE ARE NOT SURE THE SENDING FROM PROCESSOR (COMPONENT) IS ALLOWED IN CAMEL !!!
         * but we managed to do this
         * 
         * we need another Thread to execute because when sending
         * from system to itself the execution stops in waiting forever
         * due to existing running ReactiveExecutor will be found for this thread
         * and the task will be placed in it's queue while being in
         * execution of the previous task from another Workers's queue
         * of the same ReactiveExecutor   
         * 
         * Example (without separate thread): 
         * 
         * profile_s1 (ExtendedCamelContext_1 -> ReactiveExecutor_1) 
         * -> task (we're in it now!) -> [switch to ExtendedCamelContext_2] producer (vmdirect) 
         * -> ExtendedCamelContext_2 (with ReactiveExecutor_2) (route_s1)
         * -> consumer (profile_s1) 
         * -> task {
         * 		Who will execute? Let's check if there's already a ReactiveExecutor !!for current Thread!!
         * 		in target context. If no, our executor will be used.
         * 		Oh! We've found ReactiveExecutor_1, it will execute. 
         * 	} -> enqueue (ReactiveExecutor_1)
         * -> (execution is still in ExtendedCamelContext_2 - route_s1)
         * -> wait for task to be executed.
         * 
         * Result: being in previous (current) task we're waiting for the next task 
         * in the same ReactiveExecutor's queue to be executed. 
         * This will never happen.
         *   
         */
        CountDownLatch latch = new CountDownLatch(1);
        Thread exec = new Thread(new Runnable() {

            @Override
            public void run() {
                ProducerTemplate template = exchange.getContext().createProducerTemplate();
                template.send("direct-vm:profile-" + systemName + "-enter-point?block=true&timeout=60000", exchange);
                latch.countDown();
            }
        });
        exec.setContextClassLoader(Thread.currentThread().getContextClassLoader());
        exec.start();
        try {
            // we have to wait the thread to be executed
            // because we're calling synchronously
            latch.await();
        } catch (InterruptedException e) {
            // e.printStackTrace();
            log.error("Error awaiting latch", e);
        }
    }

    @Override
    public void sendTo(@Header("ENTAXY_EndpointName") String endpointName,
            @Header(HEADERS_START + ROLE) String role,
            @Header(HEADERS_START + TYPE) String type,
            @Header(HEADERS_START + SUBTYPE) String subtype,
            Exchange exchange) {
        try {
            getOutConnector(endpointName, role, type, subtype).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();
    }
}
