/*
 * JORAM: Java(TM) Open Reliable Asynchronous Messaging
 * Copyright (C) 2016 - 2024 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.admin;

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 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 BundleContext context = null;
  private ServiceRegistration<ServletContextHelper> ctxRegistration;
  private ServiceRegistration<Servlet> servletRegistration;
  public final String servletName = "joram-admin";
  public final String servletPath = "/joram/" + AdminService.ADMIN;

  public void start(BundleContext bundleContext) throws Exception {
    this.context = bundleContext;

    ClassLoader myClassLoader = getClass().getClassLoader();
    ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread().setContextClassLoader(myClassLoader);

      if (logger.isLoggable(BasicLevel.INFO))
        logger.log(BasicLevel.INFO, "Registering " + servletName + " -> " + servletPath);
      
      // initialize the admin helper
      AdminHelper.getInstance().init(bundleContext);

      // create a servlet context
      final AdminServletContext servletContext = new AdminServletContext(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 (logger.isLoggable(BasicLevel.DEBUG))
        logger.log(BasicLevel.DEBUG, "Registered context " + servletName + " -> " + ctxRegistration);

      // create and register servlets
      final Servlet servlet = new ServletContainer(new ResourceConfig(new AdminJerseyApplication().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 (logger.isLoggable(BasicLevel.DEBUG))
        logger.log(BasicLevel.DEBUG, "Registered servlet " + servletName + " -> " + servletRegistration);
    } catch (Exception exc) {
      if (logger.isLoggable(BasicLevel.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 {
    if (logger.isLoggable(BasicLevel.INFO))
      logger.log(BasicLevel.INFO, "Unregistering servlet " + servletName + " -> " + servletPath);
    if (servletRegistration != null)
      servletRegistration.unregister();
    if (ctxRegistration != null)
      ctxRegistration.unregister();
    AdminHelper.getInstance().stopJoramAdmin();
  }
}
