package r2rml.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import r2rml.engine.Configuration;
import r2rml.engine.R2RMLException;

/**
 * DB Class.
 * 
 * @author Christophe Debruyne
 * @version 0.1
 *
 */
public class DB {
	public static final String MYSQL = "MySQL";
	public static final String H2 = "H2";

	private Connection connection = null;
	private List<Statement> statements = new ArrayList<Statement>();
	private Configuration configuration = null;

	public DB(Connection connection, Configuration configuration) {
		this.connection = connection;
		this.configuration = configuration;
	}

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	public Rows getRows(String query) throws R2RMLException {
		try {
			Statement statement = connection.createStatement();
			statements.add(statement);
			if (configuration.isPreview()) {
				if (connection.getMetaData().getDatabaseProductName().equals(MYSQL)
						|| connection.getMetaData().getDatabaseProductName().equals(H2)) {
					query += " LIMIT 1";
				} else {
					query += query.contains("WHERE") ? " AND ROWNUM < 2" : " WHERE ROWNUM < 2";
				}
			}
			ResultSet resultset = statement.executeQuery(query);
			return new Rows(resultset);
		} catch (SQLException e) {
			throw new R2RMLException(e.getMessage(), e);
		}
	}

	public void close() throws R2RMLException {
		if (!statements.isEmpty()) {
			try {
				for (Statement statement : statements) {
					statement.close();
				}
				statements.clear();
			} catch (SQLException e) {
				throw new R2RMLException(e.getMessage(), e);
			}
		}

	}

}
