/**
 * 
 */
package org.richfaces.demo.datagrid.bean;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.richfaces.demo.datagrid.model.Channel;
import org.richfaces.demo.datagrid.model.Issue;
import org.richfaces.demo.datagrid.model.Key;
import org.richfaces.model.ScrollableTableDataModel;
import org.richfaces.model.SortOrder;

/**
 * @author Maksim Kaszynski
 *
 */
public class ChannelDataModel2 extends ScrollableTableDataModel {

	private final Log log = LogFactory.getLog(ChannelDataModel2.class);
	
	public static final int BIG_QUERY_DELAY = 0*1000;
	
	public static final int SMALL_QUERY_DELAY = 0*500;
	
	private Channel channel;
	
	/* (non-Javadoc)
	 * @see org.richfaces.model.GridDataModel#getObjectById(java.io.Serializable)
	 */
	@Override
	public Object getObjectById(Object id) {
		
		if (log.isTraceEnabled()) {
			log.trace(id);
		}
		
		if (SMALL_QUERY_DELAY > 0) {
			log.info("sleeping " + SMALL_QUERY_DELAY + "ms");
			
			try {
				Thread.sleep(SMALL_QUERY_DELAY);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			log.info("Awoke from slumber");
		}
		
		
		return channel.findIssueByKey((Key) id);
	}
	
	@Override
	public Object getId(Object o) {
		Issue issue = (Issue)o;
		return issue.getKey();
	}

	/* (non-Javadoc)
	 * @see org.richfaces.model.GridDataModel#loadData(int, int, org.richfaces.model.SortOrder)
	 */
	@Override
	public List <Issue> loadData(int startRow, int endRow, SortOrder sortOrder) {
		
		if (log.isTraceEnabled()){
			log.trace("startRow=" + startRow + ", endRow=" + endRow + ",sortOrder=" + sortOrder);
		}
		
		if (BIG_QUERY_DELAY > 0) {
			log.info("sleeping " + BIG_QUERY_DELAY);
			
			try {
				Thread.sleep(BIG_QUERY_DELAY);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			log.info("Awoke from slumber");
		}
		

		return channel.executeQuery(startRow, endRow, sortOrder);
	}

	/* (non-Javadoc)
	 * @see javax.faces.model.DataModel#getRowCount()
	 */
	@Override
	public int getRowCount() {
		return channel.size();
	}

	/* (non-Javadoc)
	 * @see javax.faces.model.DataModel#getWrappedData()
	 */
	@Override
	public Object getWrappedData() {
		return channel;
	}

	@Override
	public void setWrappedData(Object arg0) {
		this.channel = (Channel) arg0;
	}

}
