package com.mockobjects.sql;

import com.mockobjects.util.AssertMo;

import java.sql.SQLException;

/**
 * This is a simple implementation of a MockResultSet.
 * It returns values for multiple rows.
 * @version $Revision: 1.4 $
 */
abstract class CommonMockMultiRowResultSet extends MockResultSet {
    private Object[][] myRows = new Object[0][0];
    private String[] myColumnNames;
    private int myRowOffset = -1;

    private SQLException myGetException = null;

    public CommonMockMultiRowResultSet() {
        super();
    }

    /**
     * @param name Label used to identify mock when it errors
     */
    public CommonMockMultiRowResultSet(String name) {
        super(name);
    }

    public void setupColumnNames(String[] columnNames) {
        myColumnNames = columnNames;
    }

    public void setupRows(Object[][] rows) {
        myRows = rows;
    }

    public void setupThrowExceptionOnGet(SQLException exception) {
        myGetException = exception;
    }

    public Object getObject(int columnIndex) throws SQLException {
        throwGetExceptionIfAny();
        if (columnIndex > myRows[myRowOffset].length || columnIndex < 1) {
            AssertMo.fail("Column " + columnIndex + " not found in " + name);
        }
        return myRows[myRowOffset][columnIndex - 1];
    }

    public Object getObject(String columnName) throws SQLException {
        throwGetExceptionIfAny();
        return getObject(findIndexForColumnName(columnName));
    }

    public boolean next() throws SQLException {
        myNextCalls.inc();
        if (myRowOffset + 1 >= myRows.length) {
            return false;
        }
        myRowOffset++;
        return true;
    }

    public int getRow() throws SQLException {
        return myRowOffset + 1;
    }

    private void throwGetExceptionIfAny() throws SQLException {
        if (null != myGetException) {
            throw myGetException;
        }
    }

    private int findIndexForColumnName(String columnName) throws SQLException {
        for (int i = 0; i < myColumnNames.length; ++i) {
            if (myColumnNames[i].equalsIgnoreCase(columnName)) {
                return i + 1;
            }
        }
        throw new SQLException("Column name not found");
    }
}
