/**
 * This file is part of the Meeds project (https://meeds.io/).
 *
 * Copyright (C) 2020 - 2025 Meeds Association contact@meeds.io
 *
 * This program 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 3 of the License, or (at your option) any later version.
 * This program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.exoplatform.container.management;

import org.exoplatform.container.ConcurrentContainer;
import org.exoplatform.container.ExoContainer;
import org.exoplatform.container.jmx.MX4JComponentAdapter;
import org.exoplatform.container.spi.Container;
import org.exoplatform.management.spi.ManagementProvider;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;

import java.lang.annotation.Annotation;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.enterprise.context.Dependent;
import javax.enterprise.context.spi.CreationalContext;

public class ManageableComponentAdapter<T> extends MX4JComponentAdapter<T>
{

   /**
    * The serial version UID
    */
   private static final long serialVersionUID = 8922696628680586728L;

   /** . */
   private static final Log LOG = ExoLogger.getLogger("exo.kernel.container.ManageableComponentAdapter");

   /** . */
   private final AtomicBoolean registered = new AtomicBoolean();

   public ManageableComponentAdapter(ExoContainer holder, ConcurrentContainer container, Object key,
      Class<T> implementation)
   {
      super(holder, container, key, implementation);
   }

   protected void register(Container co, Object instance)
   {
      if (registered.compareAndSet(false, true))
      {
         do
         {
            if (co instanceof ManageableContainer)
            {
               break;
            }
         }
         while ((co = co.getSuccessor()) != null);
         if (co instanceof ManageableContainer)
         {
            ManageableContainer container = (ManageableContainer)co;
            if (container.managementContext != null)
            {
               // Register the instance against the management context
               if (LOG.isDebugEnabled())
                  LOG.debug("==> add " + instance + " to a mbean server");
               container.managementContext.register(instance);

               // Register if it is a management provider
               if (instance instanceof ManagementProvider)
               {
                  ManagementProvider provider = (ManagementProvider)instance;
                  container.addProvider(provider);
               }
            }
         }
      }
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public T create(CreationalContext<T> creationalContext)
   {
      T instance = super.create(creationalContext);
      Class<? extends Annotation> scope = null;
      if (instance != null && (((scope = getScope()) != null && !scope.equals(Dependent.class))) || isSingleton())
      {
         register(exocontainer, instance);
      }
      return instance;
   }

   /**
    * {@inheritDoc}
    */
   @Override
   public void destroy(T instance, CreationalContext<T> creationalContext)
   {
      try
      {
         Container co = exocontainer;
         do
         {
            if (co instanceof ManageableContainer)
            {
               break;
            }
         }
         while ((co = co.getSuccessor()) != null);
         if (co instanceof ManageableContainer)
         {
            ManageableContainer container = (ManageableContainer)co;
            if (container.managementContext != null)
            {
               // UnRegister the instance against the management context
               if (LOG.isDebugEnabled())
                  LOG.debug("==> remove " + instance + " from a mbean server");
               container.managementContext.unregister(instance);
            }
         }
         creationalContext.release();
      }
      catch (Exception e)
      {
         LOG.error("Could not destroy the instance " + instance + ": " + e.getMessage());
      }
   }
}
