package de.hsadmin.mods.db;

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

import de.hsadmin.core.qserv.AbstractProcessor;
import de.hsadmin.core.qserv.ProcessorException;
import de.hsadmin.core.util.Config;

public class JDBCProcessor extends AbstractProcessor {
	
	private static final long serialVersionUID = 7702753017749022325L;

	private String driver;
	private String url;
	private String user;
	private String password;
	private List<String> sql;

	public JDBCProcessor(String driver, String url, String user, String password) {
		this.driver = driver;
		this.url = url;
		this.user = user;
		this.password = password;
	}

	public JDBCProcessor(String driver, String url) {
		this.driver = driver;
		this.url = url;
	}

	public void addSQL(String sqlStatement) {
		if (sql == null)
			sql = new ArrayList<String>();
		sql.add(sqlStatement);
	}

	public Object process() throws ProcessorException {
		Connection c = null;
		Config config = Config.getInstance();
		if ("com.mysql.jdbc.Driver".equals(driver)) {
			if (user == null)
				user = config.getProperty("mysqladmin.user", "root");
			if (password == null)
				password = config.getProperty("mysqladmin.password");
		}
		if ("org.postgresql.Driver".equals(driver)) {
			if (user == null)
				user = config.getProperty("pgsqladmin.user", "postgres");
			if (password == null)
				password = config.getProperty("pgsqladmin.password");
		}
		if (user == null || password == null) {
			throw new ProcessorException("database admin-user configuration failed");
		}
		try {
			Class.forName(driver);
			c = DriverManager.getConnection(url, user, password);
			if (c == null)
				throw new ProcessorException("cannot connect to '" + url + "'");
			Statement s = c.createStatement();
			for (String sqlStatement : sql) {
				s.addBatch(sqlStatement);
				System.out.println("SQL: " + sqlStatement);
			}
			return s.executeBatch();
		} catch (SQLException aSqlExc) {
			Exception exc = aSqlExc.getNextException();
			if (exc == null)
				exc = aSqlExc;
			System.out.println("ERR: " + exc.getMessage());
			throw new ProcessorException(aSqlExc.getMessage() + ", reason: "
					+ exc.getMessage());
		} catch (Exception aExc) {
			throw new ProcessorException(aExc.getMessage());
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception exc) {
				}
			}
		}
	}
}
