/*
 * 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/>
 *   SearchableCache searchableCache = SearchableCacheFactory.createSearchableCache(coreCache, class[]);
 *
 * <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);
//       boolean isPojoCache = c instanceof PojoCache; keep this for later usage

      // Step 2: Add cache listener to listen for events happening in the cache.
      //SearchableListener listener = isPojoCache ? new SearchablePojoListener(searchFactory) : new SearchableCoreListener(searchFactory);

      SearchableCoreListener listener = new SearchableCoreListener(searchFactory);
      c.addCacheListener(listener);


      // step 3: create the searchable cache delegate.
      SearchableCache sc = new SearchableCacheImpl(c, searchFactory);
      return sc;
   }


   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());
         }
      }

   }

}
