package org.seamframework.sql;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class ExecutableStatement {
	
	private final List<Parameter<?>> parameters;
	private final PreparedStatement ps;
	
	public ExecutableStatement(Statement statement, Session session) {
		ps = session.createStatement(statement.toSql());
		parameters = statement.getParameters();
	}
	
	@SuppressWarnings("unchecked")
	public ExecutableStatement(String statement, Session session) {
		ps = session.createStatement(statement);
		parameters = Collections.EMPTY_LIST;
	}
	
	public PreparedStatement getPreparedStatement() {
		return ps;
	}

	public <T> ExecutableStatement set(Parameter<T> parameter, T value) {
		return set( parameters.indexOf(parameter), value, parameter.getType() );
	}
	
	public <T> ExecutableStatement set(int index, T value, Type<T> type) {
		try {
			if (index<0) throw new IllegalArgumentException();
			if (value==null) {
				ps.setNull(index + 1, type.getJdbcType());
			}
			else {
				ps.setObject(index + 1, value, type.getJdbcType());
			}
			return this;
		}
		catch (SQLException sqle) {
			throw new RuntimeException(sqle);
		}
	}
	
	public void execute() {
		try {
			getPreparedStatement().execute();
		}
		catch (SQLException sqle) {
			throw new RuntimeException(sqle);
		}
	}

}
