/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 Bull S.A.S
 * Contact: jonas-team@ow2.org
 *
 * This library 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 any later version.
 *
 * This library 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: PreparedStatementListCacheImpl.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.resource.internal.cm.sql.cache;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.resource.internal.cm.sql.PreparedStatementWrapper;

/**
 * Array cache implementation
 * most recently used element are kept at the end of the list
 * LRU policy for freeing element
 * @author pelletib
 */
public class PreparedStatementListCacheImpl extends AbstractPreparedStatementCacheImpl implements PreparedStatementCache {

    /**
     * Cache
     */
    public List<PreparedStatementWrapper> pStmts = null;

    /**
     * Constructor
     * @param maxCacheSize max cache size
     * @param logger trace logger
     */
    public PreparedStatementListCacheImpl(final int maxCacheSize, final PreparedStatementCacheStatistics pstmtStats, final Logger logger) {
        super(maxCacheSize,pstmtStats,logger);
        pStmts = new ArrayList<PreparedStatementWrapper>();
    }

    @Override
    public synchronized PreparedStatementWrapper get(final PreparedStatementWrapper psw) {

        int jumpNb = 0;

        PreparedStatementWrapper outputPsw = null;

        if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
            cacheLogger.log(BasicLevel.DEBUG, "MC pStmts: " + pStmts);
        }

        // update statistics
        stats.incrementPrepStmtCacheAccessCount();


        // Check if statement matches ManagedConnection list & valid
        // use lastIndexOf as when a statement is found, it is put at the end.
        int indexPstmt = pStmts.lastIndexOf(psw);

        while (indexPstmt != -1) {

            outputPsw = pStmts.get(indexPstmt);

            if (outputPsw.isClosed()) { // entry found

                outputPsw = pStmts.remove(indexPstmt);
                outputPsw.clearPstmtValues(); // clear value and mark it as open
                // before return out of the cache
                pStmts.add(outputPsw); // add last

                break;

            } else {
                outputPsw = null; // reset
                jumpNb++;
                if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
                    cacheLogger.log(BasicLevel.DEBUG, "Statement in cache but already used, search another one");
                    cacheLogger.log(BasicLevel.DEBUG, "sql=" + psw.getSql() + ", count=" + jumpNb);
                }
                // next element
                indexPstmt = pStmts.subList(0, indexPstmt).lastIndexOf(psw);
            }
        }

        if (indexPstmt != -1) { // found

            if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
                cacheLogger.log(BasicLevel.DEBUG, "Statement found in cache " + outputPsw);
            }

            // update statistics
            stats.incrementPrepStmtCacheHitCount();


        } else { // not found
            if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
                cacheLogger.log(BasicLevel.DEBUG, "No statement in cache (or not closed)");
            }
            // update statistics
            stats.incrementPrepStmtCacheMissCount();
        }

        return outputPsw;
    }



    /**
     * Put a pstmt in the cache. If the cache is full, an entry is removed first according to the LRU algorithm
     * @param psw prepared statement to add
     */
    @Override
    public synchronized void put(final PreparedStatementWrapper psw) throws CacheException, SQLException {

        // error if cache is disabled
        if (maxPstmtCacheSize < 0) {
            throw new CacheException("Cache disabled");
        }

        // update statistics
        stats.incrementPrepStmtCacheAccessCount();

        // if cache is satured, try to free an entry
        if (pstmtCacheSize >= maxPstmtCacheSize && maxPstmtCacheSize != 0) {
            int offset = findFreeStmt();
            if (offset >= 0) {
                // Remove that entry from the current pool and add it at the
                // end of the list
                PreparedStatementWrapper toRemovePsw = pStmts.remove(offset);
                toRemovePsw.destroy();
                if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
                    cacheLogger.log(BasicLevel.DEBUG, "Cache is full : removing an entry PStmt: " + toRemovePsw);
                }

                // update statistics
                pstmtCacheSize--;
                stats.incrementPrepStmtCacheDeleteCount();
                stats.decrementPrepStmtCacheCurrentSize();


            } else {
                if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
                    cacheLogger.log(BasicLevel.DEBUG, "No more space in cache");
                }

                throw new CacheException("No more space in cache");
            }
        }

        // add the entry in the cache
        pStmts.add(psw);

        if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
            cacheLogger.log(BasicLevel.DEBUG, "Adding PStmt: " + psw);
        }

        pstmtCacheSize++;

        // update statistics
        stats.incrementPrepStmtCacheAddCount();
        stats.incrementPrepStmtCacheCurrentSize();

    }

    /**
     * @param prefix indentation
     * @return a string with a cache state (dump)
     */
    @Override
    public String getState(final String prefix) {

        String res = "";

        synchronized(this) {
            res += prefix + "size of pStmts:" + pstmtCacheSize + "\n";
            for (Iterator<PreparedStatementWrapper> it = pStmts.iterator(); it.hasNext();) {
                res += prefix + "\t" + it.next() + "\n";
            }
        }

        return res;
    }

    /**
     * Destroy all the cache entries
     */
    @Override
    public synchronized void destroy() {

        if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
            cacheLogger.log(BasicLevel.DEBUG, "Destroy the cache entries");
        }

        // update statistics
        stats.incrementPrepStmtCacheAccessCount();

        PreparedStatementWrapper pw = null;

        // Remove the PreparedStatements on the MC
        while (pStmts != null && pStmts.size() > 0) {
            pw = pStmts.remove(0);
            stats.incrementPrepStmtCacheDeleteCount();
            stats.decrementPrepStmtCacheCurrentSize();
            try {
                pw.destroy();
            } catch (Exception ex) {
            }
        }
        pstmtCacheSize=0;
    }

    /**
     * Close all the cache entries
     */
    @Override
    public synchronized void reallyClose() {

        if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
            cacheLogger.log(BasicLevel.DEBUG, "Close physically the cache entries");
        }

        // update statistics
        stats.incrementPrepStmtCacheAccessCount();

        PreparedStatementWrapper pw = null;

        // Remove the PreparedStatements on the MC
        while (pStmts != null && pStmts.size() > 0) {
            pw = pStmts.remove(0);
            stats.incrementPrepStmtCacheDeleteCount();
            stats.decrementPrepStmtCacheCurrentSize();
            try {
                pw.closePstmt();
            } catch (Exception ex) {
            }
        }
        pstmtCacheSize = 0;

    }

    /**
     * Close all the cache entries
     */
    @Override
    public synchronized void close() {

        if (cacheLogger.isLoggable(BasicLevel.DEBUG)) {
            cacheLogger.log(BasicLevel.DEBUG, "Close the cache entries");
        }

        // update statistics
        stats.incrementPrepStmtCacheAccessCount();

        PreparedStatementWrapper pw = null;

        // Remove the PreparedStatements on the MC
        int stmtSize = pStmts.size();
        try {
            for (int i = 0; i < stmtSize; i++) {
                pw = pStmts.get(i);
                pw.close();
            }
        } catch (Exception ex) {
        }
    }

    /**
     * Determine if there is a pStmt to remove
     * The method calling this code should use synchronized block
     * @return int offset of the first free entry
     */
    private int findFreeStmt() {
        int offset = -1;
        int size = pStmts.size();
        PreparedStatementWrapper psw = null;
        if (pStmts != null) {
            for (int i = 0; i < size; i++) {
                psw = pStmts.get(i);
                if (psw.isClosed()) {
                    offset = i;
                    break;
                }
            }
        }
        return offset;
    }

}
