/*
 * JORAM: Java(TM) Open Reliable Asynchronous Messaging
 * Copyright (C) 2016 - 2025 ScalAgent Distributed Technologies
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s): 
 */
package org.objectweb.joram.tools.rest.jms;

import java.util.Dictionary;
import java.util.Hashtable;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.http.context.ServletContextHelper;
import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;

import fr.dyade.aaa.common.Debug;
import fr.dyade.aaa.util.management.MXWrapper;
import jakarta.servlet.Servlet;
import jakarta.ws.rs.ext.RuntimeDelegate;

/**
 *
 */
public final class Activator implements BundleActivator {
  private static final Logger logger = Debug.getLogger(Activator.class.getName());
  private static final boolean DEBUG = logger.isLoggable(BasicLevel.DEBUG);
  
  public static final String SERVICE_NAME = "rest.service.name";
  
  private BundleContext context = null;
  private ServiceRegistration<ServletContextHelper> ctxRegistration;
  private ServiceRegistration<Servlet> servletRegistration;
  public final String servletName = "joram-jms";
  public String servletPath = "/joram";
	
	private CleanerTask cleanerTask;
  
  public void start(BundleContext bundleContext) throws Exception {
    this.context = bundleContext;
          
  ClassLoader myClassLoader = getClass().getClassLoader();
  ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
  try {
    Thread.currentThread().setContextClassLoader(myClassLoader);

    String serviceName = bundleContext.getProperty(SERVICE_NAME);
    if (serviceName != null && !serviceName.isEmpty()) {
      servletPath = serviceName.startsWith("/") ? serviceName : "/" + serviceName;
    }

    if (logger.isLoggable(BasicLevel.INFO))
      logger.log(BasicLevel.INFO, "Registering " + servletName + " -> " + servletPath);

    // set properties from felix configuration
    Helper.getInstance().setGlobalProperties(bundleContext);

    // create a servlet context
    final JmsServletContext servletContext = new JmsServletContext(context.getBundle());

    System.setProperty(RuntimeDelegate.JAXRS_RUNTIME_DELEGATE_PROPERTY, "org.glassfish.jersey.internal.RuntimeDelegateImpl");

    // register the servlet context with specific name and path
    final Dictionary<String, Object> servletContextProps = new Hashtable<>();
    servletContextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, servletName);
    servletContextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, servletPath);
    ctxRegistration = context.registerService(ServletContextHelper.class, servletContext, servletContextProps);

    if (DEBUG)
      logger.log(BasicLevel.DEBUG, "Registered context " + servletName + " -> " + ctxRegistration);

    // create and register servlets
    final Servlet servlet = new ServletContainer(new ResourceConfig(new JmsJerseyApplication().getClasses()));
    final Dictionary<String, Object> servletProps = new Hashtable<>();
    servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/*");
    servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
                     "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + '=' + servletName + ')');
    servletRegistration = context.registerService(Servlet.class, servlet, servletProps);

    if (DEBUG)
      logger.log(BasicLevel.DEBUG, "Registered servlet " + servletName + " -> " + servletRegistration);

    int period = Helper.DFLT_CLEANER_PERIOD;
    String value = bundleContext.getProperty(Helper.BUNDLE_CLEANER_PERIOD_PROP);
    if (value != null && !value.isEmpty()) {
      try {
        period = Integer.parseInt(value);
        logger.log(BasicLevel.INFO,
                   "Set configuration property " + Helper.BUNDLE_CLEANER_PERIOD_PROP + " to " + value);
      } catch (NumberFormatException exc) {
        logger.log(BasicLevel.WARN,
                   "Bad configuration property " + Helper.BUNDLE_CLEANER_PERIOD_PROP + ", should be a number: " + value);
      }
    }
    Helper.getInstance().setCleanerPeriod(period);
    if (period > 0) {
      cleanerTask = new CleanerTask();
      cleanerTask.setPeriod(period);
      cleanerTask.start();
    }
    registerMBean(Helper.getInstance(), mbeanName);

    if (logger.isLoggable(BasicLevel.WARN))
      logger.log(BasicLevel.WARN, "Registered servlet " + servletName + " ok.");
  } catch (Exception exc) {
      if (DEBUG)
        logger.log(BasicLevel.WARN, "Error during " + servletName + " registration:", exc);
      else
        logger.log(BasicLevel.WARN, "Error during " + servletName + " registration: " + exc.getMessage());
    } finally {
      Thread.currentThread().setContextClassLoader(originalContextClassLoader);
    }
  }

  public void stop(BundleContext bundleContext) throws Exception {
    unregisterMBean(mbeanName);
    if (cleanerTask != null)
      cleanerTask.stop();
    Helper.getInstance().closeAll();
    
    if (logger.isLoggable(BasicLevel.INFO))
      logger.log(BasicLevel.INFO, "Unregistering servlet " + servletName + " -> " + servletPath);
    if (servletRegistration != null)
      servletRegistration.unregister();
    if (ctxRegistration != null)
      ctxRegistration.unregister();
  }
  
  private static String JMX_DOMAIN = "Joram Rest";
  private static String mbeanName = "connector=JMS";
  
  public static void registerMBean(Object mbean, String name) {
    try {
      MXWrapper.registerMBean(mbean, JMX_DOMAIN, name);
    } catch (Exception e) {
      logger.log(BasicLevel.WARN, "registerMBean: " + name, e);
    }
  }

  public static void unregisterMBean(String name) {
    try {
      MXWrapper.unregisterMBean(JMX_DOMAIN, name);
    } catch (Exception e) {
      logger.log(BasicLevel.WARN, "unregisterMBean: " + name, e);
    }
  }
}
