/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* 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.metadata.plugins.cache;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import org.jboss.logging.Logger;
import org.jboss.util.CachePolicy;

/**
 * Cache policy cache factory.
 *
 * @author <a href="mailto:ales.justin@jboss.com">Ales Justin</a>
 */
public class CachePolicyCacheFactory implements CacheFactory
{
   private static final Logger log = Logger.getLogger(CachePolicyCacheFactory.class);

   private CachePolicyFactory factory;
   private List<CachePolicy> policies;

   public CachePolicyCacheFactory(CachePolicyFactory factory)
   {
      if (factory == null)
         throw new IllegalArgumentException("Null factory");
      this.factory = factory;
      this.policies = new ArrayList<CachePolicy>();
   }

   public String createFqn(Object owner)
   {
      return null;
   }

   /**
    * Create cache policy.
    *
    * @return the cache policy
    */
   protected CachePolicy createCachePolicy()
   {
      try
      {
         CachePolicy policy = factory.createCachePolicy();
         policy.create();
         policy.start();
         policies.add(policy);
         return policy;
      }
      catch (Exception e)
      {
         if (e instanceof RuntimeException)
            throw (RuntimeException)e;
         else
            throw new RuntimeException(e);
      }
   }

   public <K, V> Cache<K, V> createCache(Class<K> keyClass, Class<V> valueClass, String rootFqn)
   {
      return new CachePolicyCache<K,V>(createCachePolicy());
   }

   public <V> CacheItem<V> createCacheItem(Class<V> valueClass, String rootFqn)
   {
      return new CachePolicyCacheItem<V>(createCachePolicy());
   }

   /**
    * Stop created policies.
    */
   public void stop()
   {
      ListIterator<CachePolicy> iter = policies.listIterator(policies.size());
      while(iter.hasPrevious())
      {
         CachePolicy policy = iter.previous();
         try
         {
            policy.stop();
         }
         catch (Throwable t)
         {
            log.debug("Exception while stopping policy: " + policy + ", problem: " + t);
         }
      }
   }

   /**
    * Destroy created policies.
    */
   public void destroy()
   {
      ListIterator<CachePolicy> iter = policies.listIterator(policies.size());
      while(iter.hasPrevious())
      {
         CachePolicy policy = iter.previous();
         try
         {
            policy.destroy();
         }
         catch (Throwable t)
         {
            log.debug("Exception while destroying policy: " + policy + ", problem: " + t);
         }
      }
      policies.clear();
   }

   @SuppressWarnings("unchecked")
   private static class CachePolicyCache<K, V> implements Cache<K, V>
   {
      private CachePolicy policy;

      private CachePolicyCache(CachePolicy policy)
      {
         if (policy == null)
            throw new IllegalArgumentException("Null policy");
         this.policy = policy;
      }

      public V put(K key, V value)
      {
         V old = (V)policy.get(key);
         policy.insert(key, value);
         return old;
      }

      public V get(K key)
      {
         return (V)policy.get(key);
      }

      public V remove(K key)
      {
         V old = (V)policy.get(key);
         policy.remove(key);
         return old;
      }

      public void clear()
      {
         policy.flush();
      }
   }

   private static class CachePolicyCacheItem<V> extends CachePolicyCache<Object, V> implements CacheItem<V>
   {
      private static final Object KEY = "<KEY>";

      private CachePolicyCacheItem(CachePolicy policy)
      {
         super(policy);
      }

      public V put(V value)
      {
         return put(KEY, value);
      }

      public V get()
      {
         return get(KEY);
      }
   }
}