/*
 * 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.sql.fn;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import woolpack.el.EL;
import woolpack.fn.Fn;

public class BeanResult<R> implements Fn<ResultSet, R, Exception> {
	private Fn<? super ResultSet, ? extends R, ? extends Exception> beanFactory;
	private Fn<String, EL, ? extends Exception> elFactory;
	
	public BeanResult(
			final Fn<? super ResultSet, ? extends R, ? extends Exception> beanFactory,
			final Fn<String, EL, ? extends Exception> elFactory) {
		this.beanFactory = beanFactory;
		this.elFactory = elFactory;
	}

	public R exec(final ResultSet c) throws Exception{
		final R r = beanFactory.exec(c);
		final ResultSetMetaData metaData = c.getMetaData();
		final int length = metaData.getColumnCount();
		for (int i = 0; i < length; i++) {
			elFactory.exec(metaData.getColumnName(i + 1)).setValue(r, c.getObject(i + 1));
		}
		return r;
	}

	public Fn<String, EL, ? extends Exception> getElFactory() {
		return elFactory;
	}
	public void setElFactory(final Fn<String, EL, ? extends Exception> elFactory) {
		this.elFactory = elFactory;
	}
	public Fn<? super ResultSet, ? extends R, ? extends Exception> getBeanFactory() {
		return beanFactory;
	}
	public void setBeanFactory(
			final Fn<? super ResultSet, ? extends R, ? extends Exception> beanFactory) {
		this.beanFactory = beanFactory;
	}
}
