/*
 *
 *    OPEN-XCHANGE legal information
 *
 *    All intellectual property rights in the Software are protected by
 *    international copyright laws.
 *
 *
 *    In some countries OX, OX Open-Xchange, open xchange and OXtender
 *    as well as the corresponding Logos OX Open-Xchange and OX are registered
 *    trademarks of the Open-Xchange, Inc. group of companies.
 *    The use of the Logos is not covered by the GNU General Public License.
 *    Instead, you are allowed to use these Logos according to the terms and
 *    conditions of the Creative Commons License, Version 2.5, Attribution,
 *    Non-commercial, ShareAlike, and the interpretation of the term
 *    Non-commercial applicable to the aforementioned license is published
 *    on the web site http://www.open-xchange.com/EN/legal/index.html.
 *
 *    Please make sure that third-party modules and libraries are used
 *    according to their respective licenses.
 *
 *    Any modifications to this package must retain all copyright notices
 *    of the original copyright holder(s) for the original code used.
 *
 *    After any such modifications, the original and derivative code shall remain
 *    under the copyright of the copyright holder(s) and/or original author(s)per
 *    the Attribution and Assignment Agreement that can be located at
 *    http://www.open-xchange.com/EN/developer/. The contributing author shall be
 *    given Attribution for the derivative code and a license granting use.
 *
 *     Copyright (C) 2004-2011 Open-Xchange, Inc.
 *     Mail: info@open-xchange.com
 *
 *
 *     This program is free software; you can redistribute it and/or modify it
 *     under the terms of the GNU General Public License, Version 2 as published
 *     by the Free Software Foundation.
 *
 *     This program 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 General Public License
 *     for more details.
 *
 *     You should have received a copy of the GNU General Public License along
 *     with this program; if not, write to the Free Software Foundation, Inc., 59
 *     Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

package com.openexchange.groupware.ldap;

import static com.openexchange.java.Autoboxing.I;
import static com.openexchange.java.Autoboxing.I2i;
import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.openexchange.cache.dynamic.impl.OXObjectFactory;
import com.openexchange.caching.Cache;
import com.openexchange.caching.CacheException;
import com.openexchange.caching.CacheKey;
import com.openexchange.caching.CacheService;
import com.openexchange.groupware.AbstractOXException;
import com.openexchange.groupware.EnumComponent;
import com.openexchange.groupware.contexts.Context;
import com.openexchange.groupware.ldap.LdapException.Code;
import com.openexchange.server.services.ServerServiceRegistry;

/**
 * This class implements the user storage using a cache to store once read
 * objects.
 */
public class CachingUserStorage extends UserStorage {

    /**
     * Logger.
     */
    private static final Log LOG = LogFactory.getLog(CachingUserStorage.class);

    private static final String REGION_NAME = "User";

    /**
     * Proxy attribute for the object implementing the persistent methods.
     */
    private final UserStorage delegate;

    /**
     * Lock for the cache.
     */
    private final Lock cacheLock;

    /**
     * Default constructor.
     */
    public CachingUserStorage(final UserStorage delegate) {
        super();
        this.delegate = delegate;
        cacheLock = new ReentrantLock(true);
    }

    @Override
    public User getUser(final int uid, final Context context) throws LdapException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (cacheService == null) {
            return delegate.getUser(uid, context);
        }
        try {
            return createProxy(context, uid, cacheService, null);
        } catch (UserException e) {
            throw new LdapException(e);
        }
    }

    private User createProxy(final Context ctx, final int userId, final CacheService cacheService, final User user) throws UserException {
        final OXObjectFactory<User> factory = new OXObjectFactory<User>() {
            public Serializable getKey() {
                return cacheService.newCacheKey(ctx.getContextId(), userId);
            }
            public User load() throws LdapException {
                return getDelegate().getUser(userId, ctx);
            }
            public Lock getCacheLock() {
                return CachingUserStorage.this.getCacheLock();
            }
        };
        try {
            return null == user ? new UserReloader(factory, REGION_NAME) : new UserReloader(factory, user, REGION_NAME);
        } catch (final AbstractOXException e) {
            if (e instanceof UserException) {
                throw (UserException) e;
            }
            throw new UserException(e);
        }
    }

    @Override
    public User getUser(final Context ctx, final int userId, Connection con) throws UserException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (cacheService == null) {
            return delegate.getUser(ctx, userId, con);
        }
        final User user = delegate.getUser(ctx, userId, con);
        return createProxy(ctx, userId, cacheService, user);
    }

    @Override
    public User[] getUser(final Context ctx) throws UserException {
        return getUser(ctx, listAllUser(ctx));
    }

    @Override
    public User[] getUser(final Context ctx, int[] userIds) throws UserException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (cacheService == null) {
            return delegate.getUser(ctx);
        }
        final Cache cache;
        try {
            cache = cacheService.getCache(REGION_NAME);
        } catch (final CacheException e) {
            throw new UserException(e);
        }
        final List<User> retval = new ArrayList<User>(userIds.length);
        final List<Integer> toLoad = new ArrayList<Integer>(userIds.length);
        final int contextId = ctx.getContextId();
        for (final int userId : userIds) {
            final OXObjectFactory<User> factory = new OXObjectFactory<User>() {
                public Serializable getKey() {
                    return cacheService.newCacheKey(contextId, userId);
                }
                public User load() throws LdapException {
                    return getDelegate().getUser(userId, ctx);
                }
                public Lock getCacheLock() {
                    return CachingUserStorage.this.getCacheLock();
                }
            };
            User user = null;
            {
                final Serializable key = factory.getKey();
                final Object object = cache.get(key);
                if (object instanceof Condition) {
                    /*
                     * Wait for another thread to load the object.
                     */
                    final Condition cond = (Condition) object;
                    final Lock lock = factory.getCacheLock();
                    lock.lock();
                    try {
                        if (cond.await(1, TimeUnit.SECONDS)) {
                            /*
                             * Another thread finished loading the object.
                             */
                            final Object tmp = cache.get(key);
                            if (tmp instanceof User) {
                                user = (User) tmp;
                            }
                        }
                    } catch (final InterruptedException e) {
                        user = null;
                    } finally {
                        lock.unlock();
                    }
                } else {
                    user = (User) object;
                }
            }
            if (null == user) {
                toLoad.add(I(userId));
            } else {
                try {
                    retval.add(new UserReloader(factory, user, REGION_NAME));
                } catch (final CacheException e) {
                    throw new UserException(e);
                }
            }
        }
        final User[] loaded = delegate.getUser(ctx, I2i(toLoad));
        for (final User user : loaded) {
            final OXObjectFactory<User> factory = new OXObjectFactory<User>() {
                public Serializable getKey() {
                    return cacheService.newCacheKey(contextId, user.getId());
                }
                public User load() throws LdapException {
                    return getDelegate().getUser(user.getId(), ctx);
                }
                public Lock getCacheLock() {
                    return CachingUserStorage.this.getCacheLock();
                }
            };
            try {
                retval.add(new UserReloader(factory, user, REGION_NAME));
            } catch (final CacheException e) {
                throw new UserException(e);
            }
        }
        return retval.toArray(new User[retval.size()]);
    }

    @Override
    public void updateUser(final User user, final Context context) throws LdapException {
        delegate.updateUser(user, context);
        try {
            invalidateUser(context, user.getId());
        } catch (final UserException e) {
            throw new LdapException(e);
        }
    }

    @Override
    public String getUserAttribute(String name, int userId, Context context) throws LdapException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (cacheService == null) {
            return delegate.getUserAttribute(name, userId, context);
        }
        final Set<String> set = getUser(userId, context).getAttributes().get(new StringBuilder("attr_").append(name).toString());
        return null == set ? null : (set.isEmpty() ? null : set.iterator().next());
    }

    @Override
    public void setUserAttribute(String name, String value, int userId, Context context) throws LdapException {
        delegate.setUserAttribute(name, value, userId, context);
        try {
            invalidateUser(context, userId);
        } catch (final UserException e) {
            throw new LdapException(e);
        }
    }

    @Override
    public void setAttribute(String name, String value, int userId, Context context) throws LdapException {
        delegate.setAttribute(name, value, userId, context);
        try {
            invalidateUser(context, userId);
        } catch (final UserException e) {
            throw new LdapException(e);
        }
    }
    
    @Override
    public int getUserId(final String uid, final Context context) throws LdapException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (null == cacheService) {
            return delegate.getUserId(uid, context);
        }
        try {
            final Cache cache = cacheService.getCache(REGION_NAME);
            final CacheKey key = cache.newCacheKey(context.getContextId(), uid);
            int identifier = -1;
            Integer tmp;
            try {
                tmp = (Integer) cache.get(key);
            } catch (final ClassCastException e) {
                tmp = null;
            }
            if (null == tmp) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Cache MISS. Context: " + context.getContextId() + " User: " + uid);
                }
                identifier = delegate.getUserId(uid, context);
                try {
                    cache.put(key, Integer.valueOf(identifier));
                } catch (final CacheException e) {
                    throw new LdapException(EnumComponent.USER, Code.CACHE_PROBLEM, e);
                }
            } else {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Cache HIT. Context: " + context.getContextId() + " User: " + uid);
                }
                identifier = tmp.intValue();
            }
            return identifier;
        } catch (final CacheException e) {
            throw new LdapException(EnumComponent.USER, Code.CACHE_PROBLEM, e);
        }
    }

    @Override
    public int[] listModifiedUser(final Date modifiedSince, final Context context) throws LdapException {
        // Caching doesn't make any sense here.
        return delegate.listModifiedUser(modifiedSince, context);
    }

    @Override
    public User searchUser(final String email, final Context context) throws LdapException {
        // Caching doesn't make any sense here.
        return delegate.searchUser(email, context);
    }

    @Override
    public int[] listAllUser(final Context ctx) throws UserException {
        return delegate.listAllUser(ctx);
    }

    @Override
    public int[] resolveIMAPLogin(final String imapLogin, final Context context) throws UserException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (null == cacheService) {
            return delegate.resolveIMAPLogin(imapLogin, context);
        }
        try {
            final Cache cache = cacheService.getCache(REGION_NAME);
            final CacheKey key = cache.newCacheKey(context.getContextId(), new StringBuilder(imapLogin.length() + 1)
                    .append('~').append(imapLogin).toString());
            final int[] identifiers;
            int[] tmp;
            try {
                tmp = (int[]) cache.get(key);
            } catch (final ClassCastException e) {
                tmp = null;
            }
            if (null == tmp) {
                identifiers = delegate.resolveIMAPLogin(imapLogin, context);
                try {
                    cache.put(key, identifiers);
                } catch (final CacheException e) {
                    throw new UserException(UserException.Code.CACHE_PROBLEM, e);
                }
            } else {
                identifiers = tmp;
            }
            return identifiers;
        } catch (final CacheException e) {
            throw new UserException(UserException.Code.CACHE_PROBLEM, e);
        }
    }

    @Override
    public void invalidateUser(final Context ctx, final int userId) throws UserException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (null != cacheService) {
            try {
                final Cache cache = cacheService.getCache(REGION_NAME);
                cache.remove(cache.newCacheKey(ctx.getContextId(), userId));
            } catch (final CacheException e) {
                throw new UserException(UserException.Code.CACHE_PROBLEM, e);
            }
        }
    }

    @Override
    protected void startInternal() {
        // Nothing to initialize.
    }

    @Override
    protected void stopInternal() throws UserException {
        final CacheService cacheService = ServerServiceRegistry.getInstance().getService(CacheService.class);
        if (cacheService != null) {
            try {
                cacheService.freeCache(REGION_NAME);
            } catch (final CacheException e) {
                throw new UserException(e);
            }
        }
    }

    UserStorage getDelegate() {
        return delegate;
    }

    Lock getCacheLock() {
        return cacheLock;
    }

}
