/*
 * 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.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import woolpack.utils.CheckUtils;

/**
 * {@link ExpressionFactory}と{@link Executable}を使用する{@link UpdatableFactory}。
 * @author nakamura
 *
 */
public class UpdatableFactoryImpl implements UpdatableFactory {
	private final ExpressionFactory factory;
	private final Executable executable;
	
	/**
	 * コンストラクタ。
	 * @param factory {@link Expression}のファクトリ。
	 * @param executable データベースにアクセスするクラス。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public UpdatableFactoryImpl(final ExpressionFactory factory, final Executable executable) {
		CheckUtils.checkNotNull(executable);
		CheckUtils.checkNotNull(factory);
		this.executable = executable;
		this.factory = factory;
	}

	public Updatable newInstance(final String id, final Map<String, List<Object>> map) {
		final Expression expression = factory.newInstance(id, map);
		return new Updatable() {
			public int update(final Map<String, List<Object>> map) {
				final UpdateCountHolder holder = new UpdateCountHolder();
				executable.execute(expression, new Fetchable() {
					public void fetch(final Statement statement)  {
						try {
							holder.count = statement.getUpdateCount();
						} catch (final SQLException e) {
							throw new IllegalStateException(e);
						}
					}
				}, map);
				return holder.count;
			}
		};
	}
	static class UpdateCountHolder {
		private int count;
	}
}
