package de.lcag.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class DbTable extends HashTable {
	private LcagProperties dbProperties = null;

	public DbTable(LcagProperties pDbProperties) {
		this.dbProperties = pDbProperties;
	}

	public void append(LcagProperties dbProperties, String sqlQuery) {
		String jdbcURL = dbProperties.getProperty("jdbcURL");
		String dbusername = dbProperties.getProperty("username");
		String dbpassword = dbProperties.getProperty("password");

		// String excelFilePath = getFileName(tableName.concat("_Export"));

		try (Connection connection = DriverManager.getConnection(jdbcURL, dbusername, dbpassword)) {
			Statement statement = connection.createStatement();

			ResultSet result = statement.executeQuery(sqlQuery);

			writeHeaderLine(result);
			writeDataLines(result);

			statement.close();

		} catch (SQLException e) {
			e.printStackTrace();
			log.error("Error while connecting to database: %s", e.getMessage());
		}

	}

	public void append(String sqlQuery) {
		this.append(this.dbProperties, sqlQuery);
	}

	/**
	 * write header line containing column names
	 * 
	 * @param result
	 * @throws SQLException
	 */
	private void writeHeaderLine(ResultSet result) throws SQLException {
		ResultSetMetaData metaData = result.getMetaData();
		int numberOfColumns = metaData.getColumnCount();

		for (int i = 1; i <= numberOfColumns; i++) {
			String columnName = metaData.getColumnName(i);

			this.addColumn(columnName);
		}
	}

	private void writeDataLines(ResultSet result) throws SQLException {
		ResultSetMetaData metaData = result.getMetaData();
		int numberOfColumns = metaData.getColumnCount();

		while (result.next()) {
			int newRow = this.newRow();

			for (int i = 1; i <= numberOfColumns; i++) {
				Object valueObject = result.getObject(i);

				this.setCellValue(newRow, i - 1, valueObject);
			}

		}
	}
}