/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (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.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */
package com.icesoft.push.servlet;

import com.icesoft.icepush.MainServlet;
import com.icesoft.net.messaging.MessageServiceClient;
import com.icesoft.net.messaging.jms.JMSAdapter;
import com.icesoft.push.LocalPushGroupManager;
import com.icesoft.push.ProductInfo;
import com.icesoft.push.messaging.PushMessageService;
import com.icesoft.util.ThreadFactory;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.icepush.Configuration;
import org.icepush.PushContext;
import org.icepush.servlet.ServletContextConfiguration;

public class ICEpushServlet
extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(ICEpushServlet.class.getName());

    private static final int DEFAULT_THREAD_POOL_SIZE = 10;

    private ScheduledThreadPoolExecutor executor;
    private MainServlet mainServlet;
    private PushMessageService pushMessageService;

    public void destroy() {
        mainServlet.shutdown();
        pushMessageService.stop();
        pushMessageService.tearDownNow();
        pushMessageService.close();
        executor.shutdownNow();
    }

    public void init(final ServletConfig servletConfig)
    throws ServletException {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.log(Level.INFO, new ProductInfo().toString());
        }
        super.init(servletConfig);
        setUp(servletConfig.getServletContext());
    }

    protected void service(final HttpServletRequest request, final HttpServletResponse response)
    throws IOException, ServletException {
        try {
            response.addHeader("X-Powered-By", ProductInfo.PRODUCT);
            mainServlet.service(request, response);
        } catch (ServletException exception) {
            throw exception;
        } catch (IOException exception) {
            throw exception;
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }

    private void setUp(final ServletContext servletContext)
    throws ServletException {
        Configuration _configuration = new ServletContextConfiguration("com.icesoft.push", servletContext);
        ThreadFactory _threadFactory = new ThreadFactory();
        _threadFactory.setPrefix(ProductInfo.PRODUCT + " Thread");
        executor =
            new ScheduledThreadPoolExecutor(
                _configuration.getAttributeAsInteger("threadPoolSize", DEFAULT_THREAD_POOL_SIZE), _threadFactory);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, ProductInfo.PRODUCT + " - Thread Pool: " + executor.getCorePoolSize());
        }
        servletContext.setAttribute("org.icepush.PushGroupManager", "com.icesoft.push.LocalPushGroupManager");
        mainServlet = new MainServlet(servletContext, false, false, executor);
        LocalPushGroupManager _localPushGroupManager = (LocalPushGroupManager)mainServlet.getPushGroupManager();
        setUpMessageService(servletContext, _configuration, _localPushGroupManager);
    }

    private void setUpMessageService(
        final ServletContext servletContext, final Configuration configuration,
        final LocalPushGroupManager localPushGroupManager)
    throws ServletException {
        pushMessageService =
            new PushMessageService(
                PushContext.getInstance(servletContext),
                new MessageServiceClient(
                    ProductInfo.PRODUCT + " MSC", new JMSAdapter(servletContext), servletContext),
                executor,
                configuration,
                true,
                localPushGroupManager);
        String _serverInfo = servletContext.getServerInfo();
        if (!_serverInfo.startsWith("JBoss Web/3.0.0-CR1") && !_serverInfo.startsWith("JBoss Web/3.0.0-CR2")) {
            if (pushMessageService.setUpNow()) {
                pushMessageService.start();
                localPushGroupManager.setPushMessageService(pushMessageService);
            } else {
                throw new ServletException("Unable to set up Push Message Service MSC.");
            }
        } else {
            new Thread(
                new Runnable() {
                    public void run() {
                        if (pushMessageService.setUpNow()) {
                            pushMessageService.start();
                            localPushGroupManager.setPushMessageService(pushMessageService);
                        } else {
                            LOGGER.log(Level.SEVERE, "Unable to set up Push Message Service MSC.");
                        }
                    }
                }
            ).start();
        }
    }
}
