/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.crud;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import woolpack.utils.CheckUtils;

/**
 * {@link PreparedStatement}を利用する{@link Executable}。
 * @author nakamura
 *
 */
public class PreparedStatementExecutor implements Executable {
	private final DataSource dataSource;
	
	/**
	 * コンストラクタ。
	 * @param dataSource  データソース。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public PreparedStatementExecutor(final DataSource dataSource) {
		CheckUtils.checkNotNull(dataSource);
		this.dataSource = dataSource;
	}
	
	public void execute(
			final Expression expression,
			final Fetchable fetchable,
			final Map<String, List<Object>> map) {
		try {
			final Connection connection = dataSource.getConnection();
			try {
				final PreparedStatement statement = connection.prepareStatement(expression.getQuery());
				try {
					final List<InputMapPointer> inputMapPointerList = expression.getInputMapPointerList();
					final int size = inputMapPointerList.size();
					for (int i = 0; i < size; i++) {
						statement.setObject(i + 1, inputMapPointerList.get(i).get(map));
					}
					statement.execute();
					fetchable.fetch(statement);
				} finally {
					statement.close();
				}
			} finally {
				connection.close();
			}
		} catch (final SQLException e) {
			throw new IllegalStateException(e);
		}
	}
}
