/*
 * Copyright 2006-2011 the Seasar Foundation and the Others.
 *
 * Licensed 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.
 */
package org.seasar.codegen.unit;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.seasar.dao.unit.S2DaoTestCase;
import org.seasar.extension.dataset.DataSet;
import org.seasar.extension.dataset.DataTable;
import org.seasar.extension.dataset.impl.DataSetImpl;
import org.seasar.framework.exception.SQLRuntimeException;
import org.seasar.framework.util.ClassUtil;
import org.seasar.framework.util.ResultSetUtil;

/**
 * 
 * @author azusa
 * 
 */
public abstract class CodeGenTestCase extends S2DaoTestCase {

    @Override
    protected boolean needTransaction() {
        return true;
    }

    public CodeGenTestCase(String name) {
        super(name);
    }

    protected void setUpTable(String path) {
        DataSet dataSet = readXls(path);
        writeDb(dataSet);
    }

    protected void assertTable(String tableName) {
        assertTable(ClassUtil.getShortClassName(getClass()) + "_" + getName() + ".xls", tableName);
    }

    protected void assertTable(String path, String tableName) {
        DataTable expect = readXls(path).getTable(tableName);
        DataTable cnt = readDbByTable(tableName);
        DataTable actual = reload(expect);

        assertEquals("rowSize not match!", expect.getRowSize(), cnt.getRowSize());
        assertEquals(expect, actual);

    }

    protected void writeXlsFromDb(String schemaName) {
        ResultSet rsTable = null;
        DataSet dataSet = new DataSetImpl();
        try {
            rsTable = getDatabaseMetaData().getTables(null, schemaName, "%", null);
            while (rsTable.next()) {
                String tableName = rsTable.getString("TABLE_NAME");
                DataTable table = readDbByTable(tableName);
                dataSet.addTable(table);
            }
        } catch (SQLException e) {
            throw new SQLRuntimeException(e);
        } finally {
            ResultSetUtil.close(rsTable);
        }
        writeXls(schemaName + ".xls", dataSet);
    }

}
