package org.infinispan.rhq;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mc4j.ems.connection.EmsConnection;
import org.mc4j.ems.connection.bean.EmsBean;
import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
import org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent;
import org.rhq.plugins.jmx.util.ObjectNameQueryUtility;

import javax.management.ObjectName;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Discovery class for individual cache instances
 *
 * @author Heiko W. Rupp
 * @author Galder Zamarreño
 */
public class CacheDiscovery extends MBeanResourceDiscoveryComponent<CacheManagerComponent> {
   private static final Log log = LogFactory.getLog(CacheDiscovery.class);

   /** Run the discovery */
   @Override
   public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<CacheManagerComponent> ctx) {
      boolean trace = log.isTraceEnabled();
      if (trace) log.trace("Discover resources with context");
      Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();

      EmsConnection conn = ctx.getParentResourceComponent().getEmsConnection();
      if (trace) log.trace("Connection to ems server established");

      String pattern = getAllCachesPattern(ctx.getParentResourceContext().getResourceKey());
      if (trace) log.trace("Pattern to query is " + pattern);

      ObjectNameQueryUtility queryUtility = new ObjectNameQueryUtility(pattern);
      List<EmsBean> beans = conn.queryBeans(queryUtility.getTranslatedQuery());
      if (trace) log.trace("Querying "+queryUtility.getTranslatedQuery()+" returned beans: " + beans);

      for (EmsBean bean : beans) {
         // Filter out spurious beans
         if (CacheComponent.isCacheComponent(bean, "Cache")) {
            /* A discovered resource must have a unique key, that must
             * stay the same when the resource is discovered the next
             * time */
            String name = bean.getAttribute("CacheName").getValue().toString();
            String mbeanCacheName = bean.getBeanName().getKeyProperty("name");
            if (trace) log.trace("Resource name is "+name+" and resource key "+ mbeanCacheName);
            DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
                  ctx.getResourceType(), // Resource Type
                  mbeanCacheName, // Resource Key
                  name, // Resource name
                  null, // Version
                  "One cache within Infinispan", // ResourceDescription
                  ctx.getDefaultPluginConfiguration(), // Plugin Config
                  null // ProcessInfo
            );

            // Add to return values
            discoveredResources.add(detail);
            log.info("Discovered new ...  " + bean.getBeanName().getCanonicalName());
         } else {
            log.warn(String.format("MBeanServer returned spurious object %s", bean.getBeanName().getCanonicalName()));
         }
      }
      return discoveredResources;
   }

   private String getAllCachesPattern(String cacheManagerName) {
      return cacheComponentPattern(cacheManagerName, "Cache") + ",*";
   }

   protected static String cacheComponentPattern(String cacheManagerName, String componentName) {
      return "*:type=Cache,component=" + componentName + ",manager=" + ObjectName.quote(cacheManagerName);
   }
}
