/*-
 * ~~~~~~licensing~~~~~~
 * events-handler
 * ==========
 * Copyright (C) 2020 - 2023 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.core.events.handler;

import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.system.common.util.PropertiesHelper;
import ru.entaxy.esb.system.core.events.handler.util.EventHelper;
import ru.entaxy.esb.system.core.events.jpa.entity.SystemSubscription;

import javax.jms.*;
import java.util.List;

public class SubscriptionProcessingGenerator {

    private static final Logger LOG = LoggerFactory.getLogger(SubscriptionProcessingGenerator.class);

    private EventHelper eventHelper;
    private PropertiesHelper propertiesHelper;
    private javax.jms.ConnectionFactory connectionFactory;

    public void construct(Exchange exchange) throws Exception {
        List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();

        //consumer will created automatically with route
//		if (subscriptions != null && !subscriptions.isEmpty()) {
//			for (SystemSubscription subscription : subscriptions) {
//				LOG.debug("Prepare consumer topic: " + subscription.getEventTopic().getName() + " system: " + subscription.getSystem().getName());
//				createDurableConsumer(subscription);
//			}
//		}

        SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
        exchange.getContext().addRoutes(generator);
    }

    private void createDurableConsumer(SystemSubscription subscription) throws JMSException {
        try (Connection conn = connectionFactory.createConnection()) {
            conn.setClientID(eventHelper.getClientId(subscription));

            Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(subscription.getEventTopic().getName());

            session.createDurableConsumer(topic, EventHelper.CONSUMER_NAME);
            session.close();
        }
    }

    public void destruct(Exchange exchange) throws Exception {
        List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();

        boolean processRoute = exchange.getIn().getHeader("processRoute", false, Boolean.class);

        if (processRoute) {
            SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
            generator.deleteRoutes(exchange.getContext());
        }

        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (SystemSubscription subscription : subscriptions) {
                LOG.debug("Delete consumer topic: " + subscription.getEventTopic().getName() + " system " + subscription.getSystem().getName());
                purgeConsumerQueue(subscription);
                deleteConsumer(subscription);
            }
        }
    }

    private void deleteConsumer(SystemSubscription subscription) throws JMSException {
        try (Connection conn = connectionFactory.createConnection()) {
            Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

            session.unsubscribe(eventHelper.getClientId(subscription));
            session.close();
        }
    }

    private void purgeConsumerQueue(SystemSubscription subscription) throws JMSException {
        try (Connection conn = connectionFactory.createConnection()) {
            Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Topic topic = session.createTopic(subscription.getEventTopic().getName());
            MessageConsumer consumer = session.createSharedConsumer(topic, eventHelper.getClientId(subscription));

            conn.start();

            Message message = null;
            do {
                message = consumer.receive(500);
            } while (message != null);

            conn.stop();
            session.close();
        }
    }

//	public void constructRoute(Exchange exchange) throws Exception {
//		List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();
//		
//		SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
//		exchange.getContext().addRoutes(generator);
//	}

    public void destructRoute(Exchange exchange) throws Exception {
        List<SystemSubscription> subscriptions = (List<SystemSubscription>) exchange.getIn().getBody();

        SubscriptionRouteGenerator generator = new SubscriptionRouteGenerator(subscriptions, eventHelper, propertiesHelper);
        generator.deleteRoutes(exchange.getContext());
    }

    public EventHelper getEventHelper() {
        return eventHelper;
    }

    public void setEventHelper(EventHelper eventHelper) {
        this.eventHelper = eventHelper;
    }

    public PropertiesHelper getPropertiesHelper() {
        return propertiesHelper;
    }

    public void setPropertiesHelper(PropertiesHelper propertiesHelper) {
        this.propertiesHelper = propertiesHelper;
    }

    public javax.jms.ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    public void setConnectionFactory(javax.jms.ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

}
