package org.apache.torque.manager;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jcs.access.GroupCacheAccess;
import org.apache.jcs.access.exception.CacheException;
import org.apache.torque.TorqueException;

/**
 * This class provides a cache for convenient storage of method
 * results.
 *
 * @author <a href="mailto:jmcnally@collab.net">John McNally</a>
 * @version $Id: MethodResultCache.java 1379317 2012-08-31 06:56:48Z tfischer $
 */
public class MethodResultCache
{
    /** The underlying jcs cache. */
    private GroupCacheAccess jcsCache;

    /** All chache groups which are currently filled. */
    private Map<String, Object> groups;

    /** Logging */
    private static Log log = LogFactory.getLog(MethodResultCache.class);

    /**
     * Constructor
     *
     * @param cache the cache instance to use
     */
    public MethodResultCache(GroupCacheAccess cache)
    {
        this.jcsCache = cache;
        groups = new HashMap<String, Object>();
    }

    /**
     * Allows subclasses to have ctors that do not require a cache.
     * This is used by NullMethodResultCache which has no-op versions
     * of all methods.
     */
    protected MethodResultCache()
    {
        //empty
    }

    /**
     * Clear the cache
     */
    public void clear()
    {
        if (jcsCache != null)
        {
            try
            {
                jcsCache.clear();
                groups.clear();
            }
            catch (CacheException ce)
            {
                log.error(new TorqueException(
                    "Could not clear cache due to internal JCS error.", ce));
            }
        }
    }

    protected Object getImpl(MethodCacheKey key)
    {
        Object result = null;
        if (jcsCache != null)
        {
            synchronized (this)
            {
                result = jcsCache.getFromGroup(key, key.getGroupKey());
            }
        }

        if (result != null && log.isDebugEnabled())
        {
            log.debug("MethodResultCache saved expensive operation: " + key);
        }

        return result;
    }


    protected Object putImpl(MethodCacheKey key, Object value)
        throws TorqueException
    {
        //register the group, if this is the first occurrence
        String group = key.getGroupKey();
        if (!groups.containsKey(group))
        {
            groups.put(group, null);
        }

        Object old = null;
        if (jcsCache != null)
        {
            try
            {
                synchronized (this)
                {
                    old = jcsCache.getFromGroup(key, group);
                    jcsCache.putInGroup(key, group, value);
                }
            }
            catch (CacheException ce)
            {
                throw new TorqueException
                    ("Could not cache due to internal JCS error", ce);
            }
        }
        return old;
    }

    protected Object removeImpl(MethodCacheKey key)
    {
        Object old = null;
        if (jcsCache != null)
        {
            synchronized (this)
            {
                old = jcsCache.getFromGroup(key, key.getGroupKey());
                jcsCache.remove(key, key.getGroupKey());
            }
        }
        return old;
    }

    /**
     * Get an object from the method cache
     *
     * @param instanceOrClass the Object on which the method is invoked.  if
     * the method is static, a String representing the class name is used.
     * @param method the method name
     * @param arg optional arguments for the method
     *
     * @return the object or null if it does not exist
     */
    @SuppressWarnings("unchecked")
    public <T> T get(Serializable instanceOrClass, String method, Serializable ... arg)
    {
        T result = null;
        if (jcsCache != null)
        {
            try
            {
                MethodCacheKey key = new MethodCacheKey(instanceOrClass, method, arg);
                result = (T) getImpl(key);
            }
            catch (Exception e)
            {
                log.error("Problem getting object from cache", e);
            }
        }

        return result;
    }

    /**
     * Put an object into the method cache
     *
     * @param value the object to put into the cache
     * @param instanceOrClass the Object on which the method is invoked.  if
     * the method is static, a String representing the class name is used.
     * @param method the method name
     * @param arg optional arguments for the method
     */
    public <T> void put(T value, Serializable instanceOrClass, String method, Serializable ... arg)
    {
        try
        {
            MethodCacheKey key = new MethodCacheKey(instanceOrClass, method, arg);
            putImpl(key, value);
        }
        catch (Exception e)
        {
            log.error("Problem putting object into cache", e);
        }
    }

    /**
     * Remove all objects of the same group
     *
     * @param instanceOrClass the Object on which the method is invoked.  if
     * the method is static, a String representing the class name is used.
     * @param method the method name
     */
    public void removeAll(Serializable instanceOrClass, String method)
    {
        if (jcsCache != null)
        {
            try
            {
                MethodCacheKey key = new MethodCacheKey(instanceOrClass, method);
                String groupName = key.getGroupKey();
                jcsCache.invalidateGroup(groupName);
                groups.remove(groupName);
            }
            catch (Exception e)
            {
                log.error("Problem removing all", e);
            }
        }
    }

    /**
     * Remove object from method cache
     *
     * @param instanceOrClass the Object on which the method is invoked.  if
     * the method is static, a String representing the class name is used.
     * @param method the method name
     * @param arg optional arguments for the method
     *
     * @return the removed object
     */
    @SuppressWarnings("unchecked")
    public <T> T remove(Serializable instanceOrClass, String method, Serializable ... arg)
    {
        T result = null;
        if (jcsCache != null)
        {
            try
            {
                MethodCacheKey key = new MethodCacheKey(instanceOrClass, method, arg);
                result = (T) removeImpl(key);
            }
            catch (Exception e)
            {
                log.error("Problem removing object from cache", e);
            }
        }

        return result;
    }
}
