/*-
 * ~~~~~~licensing~~~~~~
 * events-handler
 * ==========
 * 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.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;
    }

}
