/*
 * JBoss, Home of Professional Open Source
 * Copyright ${year}, Red Hat Middleware LLC, and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.cache.search;

import org.hibernate.search.impl.SearchFactoryImpl;
import org.hibernate.search.cfg.SearchConfiguration;
import org.hibernate.search.engine.SearchFactoryImplementor;
import org.jboss.cache.Cache;
import org.jboss.cache.CacheStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Properties;
import java.lang.reflect.Field;

/**
 * Factory class used to create the searchable-cache like so: -
 * <p/>
 * <p/>
 * SearchableCache searchableCache = SearchableCacheFactory.createSearchableCache(coreCache, class[]);
 * <p/>
 * <p/>
 *
 * @author Navin Surtani (<a href="mailto:nsurtani@redhat.com">nsurtani@redhat.com</a>)
 */
public class SearchableCacheFactory
{
   private static final Log log = LogFactory.getLog(SearchableCacheFactory.class);


   /**
    * Creates a searchable cache from a cache object and a class array, without the properties object.
    *
    * @param c       - the Cache
    * @param classes - Class array to be added
    * @return a SearchableCache
    */
   public SearchableCache createSearchableCache(Cache<?, ?> c, Class... classes)
   {
      return createSearchableCache(c, null, classes);
   }

   /**
    * This method creates a searchable cache as well but requires the properties object.
    *
    * @param c          - the Cache
    * @param properties - java.util.properties
    * @param classes    - a class array
    * @return a SearchableCache
    */
   public SearchableCache createSearchableCache(Cache<?, ?> c, Properties properties, Class... classes)
   {

      //validate the classes first. make sure the correct annotations are put in.

      validateClasses(classes);

      // assume cache is already created and running.
      // otherwise, start the cache!!
      if (c.getCacheStatus() != CacheStatus.STARTED)
      {
         if (log.isInfoEnabled()) log.info("Cache not started.  Starting cache first.");
         c.start();
      }

      if (classes.length == 0)
      {
         if (log.isWarnEnabled()) log.warn("You haven't passed in any classes to index.  Is this an error?");
      }

      // step 1: create hibernate search searchFactory
      SearchConfiguration cfg = new SearchableCacheConfiguration(classes, properties);
      // set classes in the cfg

      SearchFactoryImplementor searchFactory = new SearchFactoryImpl(cfg);


      // Okay, create the core listener
      SearchableCoreListener coreListener = new SearchableCoreListener(searchFactory);
      c.addCacheListener(coreListener);

      //Create the searchableCache and pass it on.
      SearchableCache sc = new SearchableCacheImpl(c, searchFactory);
      return sc;
   }


//   /**
//    * This method creates a searchable cache as well but requires the properties object.
//    *
//    * @param pojo          - the pojoCache
//    * @param properties - java.util.properties
//    * @param classes    - a class array
//    * @return a SearchableCache
//    */

//   public SearchableCache createSearchableCache(PojoCache pojo, Properties properties, Class... classes)
//   {
//
//      System.out.println("create searchable cache called with pojo cache");
//      //TODO: Ask Manik and/or Jason if there is a way to directly check if the pojo cache is started or not
//      validateClasses(classes);
//
//      Cache coreCache = pojo.getCache();
//
//      if (coreCache.getCacheStatus() != CacheStatus.STARTED)
//      {
//         if (log.isInfoEnabled()) log.info("Cache not started.  Starting cache first.");
//         pojo.start();
//      }
//
//      if (classes.length == 0)
//      {
//         if (log.isWarnEnabled()) log.warn("You haven't passed in any classes to index.  Is this an error?");
//      }
//
//      // step 1: create hibernate search searchFactory
//      SearchConfiguration cfg = new SearchableCacheConfiguration(classes, properties);
//      // set classes in the cfg
//
//      SearchFactoryImplementor searchFactory = new SearchFactoryImpl(cfg);
//
//      //Now create the pojoListener
//      SearchablePojoListener pojoListener = new SearchablePojoListener(searchFactory);
//      pojo.addListener(pojoListener);
//      pojo.getCache().addCacheListener(pojoListener);
//
//      SearchableCache sc = new SearchableCacheImpl(coreCache, searchFactory);
//      return sc;
//   }

//   /**
//    * Creates a searchable cache from a cache object and a class array, without the properties object.
//    *
//    * @param pojo       - the pojoCache
//    * @param classes - Class array to be added
//    * @return a SearchableCache
//    */
//
//
//   public SearchableCache createSearchableCache(PojoCache pojo, Class... classes)
//   {
//      return createSearchableCache(pojo, null, classes);
//   }

   //This is to check that both the @ProvidedId is present and the the @DocumentId is not present. This is because
   // don't want both of these 2 annotations used at the same time.
   private void validateClasses(Class... classes)
   {
      for (Class c : classes)
      {
         if (!c.isAnnotationPresent(org.hibernate.search.annotations.ProvidedId.class))
         {
            throw new IllegalArgumentException("There is no provided id on " + c.getName() + " class");
         }

         for (Field field : c.getFields())
         {
            if (field.getAnnotation(org.hibernate.search.annotations.DocumentId.class) != null)
            {
               throw new IllegalArgumentException("Please remove the documentId annotation in " + c.getName());
            }
         }
      }

   }

}
