/*
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

// ------------------------------------------------------------------------ 78

/**
 * Abstract Connection for use with mock testing.
 * Can verify the expected SQL strings with PreparedStatement or Statement
 * instances (mock versions can be used).
 * Can verify the state of closed and autoCommit.
 * Can verify the number of calls to close, commit, createStatement, and
 * rollBack.
 * Exceptions to throw can be registered for calling createStatement,
 * preparedStatement, or close.
 * Several less-often-used methods are not implemented.
 * If a notImplemented method is needed for your project, please submit
 * a patch.
 * @see <a href="http://java.sun.com/j2se/1.3/docs/api/java/sql/Connection.html">javax.sql.Connection</a>
 * @author
 * @author Jeff Martin
 * @author Ted Husted
 * @version $Revision: 1.7 $ $Date: 2003/02/21 12:17:38 $
 */
package com.mockobjects.sql;

import com.mockobjects.*;

import java.sql.*;
import java.util.Map;

abstract class CommonMockConnection extends MockObject implements Connection {

// -------------------------------------------------------------------- fields

    private boolean autoCommit = false;

    private final ExpectationValue myResultSetConcurrency;
    private final ExpectationValue myResultSetType;

    private final ExpectationList myAutoCommit;
    private final ExpectationCounter myCloseCalls;
    private final ExpectationCounter myCommitCalls;
    private final ExpectationCounter myCreateStatementCalls;

    private boolean myIsClosed;

    private SQLException myCloseException;

    private SQLException myIsClosedException;

    private DatabaseMetaData myMetaData;

    /**
     * @deprecated
     * @see CommonMockConnection2
     */
    private final ReturnObjectList myPreparedStatements;

    /**
     * @deprecated use myPreparedStatementsBag
     * @see CommonMockConnection2
     */
    private final ExpectationCollection myPreparedStatementStrings;

    private final ExpectationCounter myRollbackCalls;

    private Statement myStatement;

    private SQLException myStatementException = null;

    public CommonMockConnection() {
        this(CommonMockConnection.class.getName());
    }

    public CommonMockConnection(String name) {
        myAutoCommit = new ExpectationList(name + ".setAutoCommit");
        myCloseCalls = new ExpectationCounter(name + ".close");
        myCommitCalls = new ExpectationCounter(name + ".commit");
        myCreateStatementCalls = new ExpectationCounter(name + ".createStatement");
        myPreparedStatements = new ReturnObjectList(name + ".PreparedStatements");
        myPreparedStatementStrings = new ExpectationList(name + ".preparedStatementString");
        myRollbackCalls = new ExpectationCounter(name + ".rollback");
        myResultSetType = new ExpectationValue(name + ".resultSetType");
        myResultSetConcurrency = new ExpectationValue(name + ".resultSetConcurrency");
    }

    /**
     * @deprecated
     * Add an SQL string to use with a prepared staement.
     */
    public void addExpectedPreparedStatementString(String sql) {
        myPreparedStatementStrings.addExpected(sql);
    }

// --------------------------------------------------------------- setExpected

    /**
     * Register the anticipated value for autoCommit during testing.
     */
    public void addExpectedAutoCommit(boolean autoCommit) {
        myAutoCommit.addExpected(new Boolean(autoCommit));
    }


    /**
     * Register the number of close calls the test should make.
     * The valid method will report any discrepancy with the
     * actual count.
     */
    public void setExpectedCloseCalls(int callCount) {
        myCloseCalls.setExpected(callCount);
    }

    /**
     * Register the number of commit calls the test should make.
     * The valid method will report any discrepancy with the
     * actual count.
     */
    public void setExpectedCommitCalls(int callCount) {
        myCommitCalls.setExpected(callCount);
    }

    /**
     * Register the number of create statement calls the test should make.
     * The valid method will report any discrepancy with the
     * actual count.
     */
    public void setExpectedCreateStatementCalls(int calls) {
        myCreateStatementCalls.setExpected(calls);
    }

    /**
     * Register the number of roll back calls the test should make.
     * The valid method will report any discrepancy with the
     * actual count.
     */
    public void setExpectedRollbackCalls(int callCount) {
        myRollbackCalls.setExpected(callCount);
    }

// --------------------------------------------------------------------- setup

    /**
     * Sets expectations about the possible value of the
     * <code>resultSetConcurrency</code> parameter of
     * {@link #createStatement(int, int) createStatement()} calls.
     *
     * @param resultSetConcurrency One of the constants starting with CONCUR
     * in {@link java.sql.ResultSet}.
     */
    public void setExpectedResultSetConcurrency(int resultSetConcurrency) {
        myResultSetConcurrency.setExpected(resultSetConcurrency);
    }

    /**
     * Sets expectations about the possible value of the
     * <code>resultSetType</code> parameter of
     * {@link #createStatement(int, int) createStatement()} calls.
     *
     * @param resultSetType One of the constants starting with TYPE
     * in {@link java.sql.ResultSet}.
     */
    public void setExpectedResultSetType(int resultSetType) {
        myResultSetType.setExpected(resultSetType);
    }


    /**
     * @deprecated
     * Adds a PreparedStatement to be return by prepareStatement
     * @see CommonMockConnection2
     */
    public void setupAddPreparedStatement(PreparedStatement prepared) {
        myPreparedStatements.addObjectToReturn(prepared);
    }

    /**
     * Pass the SQL exception to throw if close is called
     * during a test.
     */
    public void setupCloseException(SQLException aCloseException) {
        myCloseException = aCloseException;
    }

    /**
     * @deprecated Use setupIsClosed
     */
    public void setupIsClose(boolean aIsClosed) {
        myIsClosed = aIsClosed;
    }

    /**
     * Pass the value to return if isClosed is called during a test.
     * This is returned unless an isClosedException has been set.
     */
    public void setupIsClosed(boolean aIsClosed) {
        myIsClosed = aIsClosed;
    }

    /**
     * Pass the SQL exception instance to throw if isClosed
     * is called during a test.
     */
    public void setupIsClosedException(SQLException aIsClosedException) {
        myIsClosedException = aIsClosedException;
    }

    /**
     * Pass the DataBaseMetaData instance for use with tests.
     */
    public void setupMetaData(DatabaseMetaData metaData) {
        myMetaData = metaData;
    }

    /**
     * Pass the Statement instance for use with tests.
     */
    public void setupStatement(Statement statement) {
        myStatement = statement;
    }

    /**
     * Pass the SQL exception to throw if preparedStatement or createStatement
     * is called during a test.
     */
    public void setupThrowExceptionOnPrepareOrCreate(SQLException exception) {
        myStatementException = exception;
    }

    public void setupAutoCommit(boolean autoCommitToReturn) {
        autoCommit = autoCommitToReturn;
    }

// --------------------------------------------------------------------- throw

    /**
     * Throw the Statement instance passed to
     * setupThrowExceptionOnPrepareOrCreate, if any.
     */
    void throwStatementExceptionIfAny() throws SQLException {
        if (null != myStatementException) {
            throw myStatementException;
        }
    }

// --------------------------------------------------------------- implemented

    /**
     * Will throw the CloseException if it has been set,
     * or otherwise increment the number or close calls.
     */
    public void close() throws SQLException {
        if (myCloseException != null) {
            throw myCloseException;
        }
        myCloseCalls.inc();
    }

    /**
     * Increments the number of commit calls.
     */
    public void commit() throws SQLException {
        myCommitCalls.inc();
    }

    /**
     * Will throw either of the statement exceptions if one has been
     * set,
     * or otherwise return the Statement passed to
     * setupStatement.
     */
    public Statement createStatement() throws SQLException {
        myCreateStatementCalls.inc();
        throwStatementExceptionIfAny();
        return myStatement;
    }

    /**
     * Returns the DatabaseMetaData instance passed to setupMetaData.
     */
    public DatabaseMetaData getMetaData()
        throws SQLException {
        return myMetaData;
    }

    /**
     * Throw the isClosedException if it has been set,
     * or otherwise return the value passed to setupIsClosed.
     */
    public boolean isClosed() throws SQLException {
        if (myIsClosedException != null) {
            throw myIsClosedException;
        }
        return myIsClosed;
    }

    /**
     * Throws a statement exception if one has been registered
     * (@see throwStatementExceptionIfAny)
     * or returns the next PreparedStatement instance passed to
     * setupAddPreparedStatement.
     */
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        myPreparedStatementStrings.addActual(sql);
        throwStatementExceptionIfAny();
        return (PreparedStatement) myPreparedStatements.nextReturnObject();
    }

    /**
     * Increments the number of roll back calls.
     */
    public void rollback() throws SQLException {
        myRollbackCalls.inc();
    }

    /**
     * Stores the value passed for comparison with the value passed
     * to setupAutoCommit.
     * The validate method will report any discrepency.
     */
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        myAutoCommit.addActual(new Boolean(autoCommit));
    }

// ------------------------------------------------------------ notImplemented

    /**
     * Calls notImplemented.
     */
    public void clearWarnings() throws SQLException {
        notImplemented();
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public Statement createStatement(
        int resultSetType,
        int resultSetConcurrency)
        throws SQLException {
        myCreateStatementCalls.inc();
        throwStatementExceptionIfAny();

        myResultSetType.setActual(resultSetType);
        myResultSetConcurrency.setActual(resultSetConcurrency);

        return myStatement;
    }

    public boolean getAutoCommit() throws SQLException {
        return autoCommit;
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public String getCatalog() throws SQLException {
        notImplemented();
        return null;
    }

    /**
     * Calls notImplemented. Returns 0.
     */
    public int getTransactionIsolation() throws SQLException {
        notImplemented();
        return 0;
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public Map getTypeMap() throws SQLException {
        notImplemented();
        return null;
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public SQLWarning getWarnings() throws SQLException {
        notImplemented();
        return null;
    }

    /**
     * Calls notImplemented. Returns false.
     */
    public boolean isReadOnly() throws SQLException {
        notImplemented();
        return false;
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public String nativeSQL(String sql) throws SQLException {
        notImplemented();
        return null;
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public CallableStatement prepareCall(String sql)
        throws SQLException {
        notImplemented();
        return null;
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public CallableStatement prepareCall(
        String sql,
        int resultSetType,
        int resultSetConcurrency)
        throws SQLException {
        notImplemented();
        return null;
    }

    /**
     * Calls notImplemented. Returns null.
     */
    public PreparedStatement prepareStatement(
        String sql,
        int resultSetType,
        int resultSetConcurrency)
        throws SQLException {
        notImplemented();
        return null;
    }

    /**
     * Calls notImplemented.
     */
    public void setCatalog(String catalog) throws SQLException {
        notImplemented();
    }

    /**
     * Calls notImplemented.
     */
    public void setReadOnly(boolean readOnly) throws SQLException {
        notImplemented();
    }

    /**
     * Calls notImplemented.
     */
    public void setTransactionIsolation(int level)
        throws SQLException {
        notImplemented();
    }

    /**
     * Calls notImplemented.
     */
    public void setTypeMap(Map map) throws SQLException {
        notImplemented();
    }

    public void setHoldability(int holdability) throws SQLException {
        notImplemented();
    }

    public int getHoldability() throws SQLException {
        notImplemented();
        return 0;
    }

    public Statement createStatement(int resultSetType, int resultSetConcurrency,
        int resultSetHoldability) throws SQLException {
        notImplemented();
        return null;
    }

    public PreparedStatement prepareStatement(String sql, int resultSetType,
        int resultSetConcurrency, int resultSetHoldability)
        throws SQLException {
        notImplemented();
        return null;
    }

    public CallableStatement prepareCall(String sql, int resultSetType,
        int resultSetConcurrency,
        int resultSetHoldability) throws SQLException {
        notImplemented();
        return null;
    }

    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
        throws SQLException {
        notImplemented();
        return null;
    }

    public PreparedStatement prepareStatement(String sql, int columnIndexes[])
        throws SQLException {
        notImplemented();
        return null;
    }

    public PreparedStatement prepareStatement(String sql, String columnNames[])
        throws SQLException {
        notImplemented();
        return null;
    }

}
