/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.ibatis;

import nuts.core.orm.dao.DataHandler;

import com.ibatis.sqlmap.client.event.RowHandler;

/**
 */
@SuppressWarnings("unchecked")
public class IBatisRowHandler implements RowHandler {
	private DataHandler dataHandler;
	private int start = 0;
	private int limit = Integer.MAX_VALUE;
	private int position = 0;
	private int count = 0;
	private boolean success = true;
	
	
	/**
	 * @param dataHandler data handler
	 */
	public IBatisRowHandler(DataHandler dataHandler) {
		this.dataHandler = dataHandler;
	}
	
	/**
	 * @param dataHandler data handler
	 */
	public IBatisRowHandler(DataHandler dataHandler, int start, int limit) {
		this.dataHandler = dataHandler;
		this.start = start;
		this.limit = limit;
	}

	/**
	 * @return the count
	 */
	public int getCount() {
		return count;
	}

	public void handleRow(Object data) {
		try {
			if (success) {
				if (position >= start && position - start < limit) {
					success = dataHandler.handleData(data);
					count++;
				}
			}
		}
		catch (Exception e) {
			throw new RuntimeException("Data Handle Error: " + data, e);
		}
	}
} 
