/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
// Package
package gov.va.med.fw.report.jasperreport.data;

// Java classes
import java.util.Collection;
import java.util.Map;
import java.util.Iterator;

// Library classes
import org.springframework.util.CollectionUtils;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;

// Framework classes
import gov.va.med.fw.report.data.ReportData;

/**
 * Encapsulates logics to create the appropriate JRDataSource 
 * based on the class type of a collection. 
 *
 * Project: Framework</br>
 * Created on: 4:24:52 PM </br>
 *
 * @author DNS   LEV
 */
public class JasperReportData extends ReportData {

	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 6868264367116166820L;

	/**
	 * An instance of jasperDataSource
	 */
	private JRDataSource jasperDataSource = null;
	
	/**
	 * A default constructor
	 * @param data
	 */
	public JasperReportData( Collection data ) {
		this( createDataSource( data ) );
	}
	
	/**
	 * A default constructor
	 * @param dataSource
	 */
	public JasperReportData( JRDataSource dataSource ) {
		super();
		this.jasperDataSource = dataSource;
	}

	/**
	 * @return Returns the jasperDataSource.
	 */
	public JRDataSource getJasperDataSource() {
		return jasperDataSource;
	}
	
	/**
	 * @param data
	 * @return
	 */
	protected static JRDataSource createDataSource( Collection data ) {
		JRDataSource source = null;
		if( CollectionUtils.isEmpty( data ) ) {
			source = new JREmptyDataSource();
		}
		else {
			for( Iterator i=data.iterator(); i.hasNext(); ) {
				Object element = i.next();
				if( element instanceof Map ) {
					source = new JRMapCollectionDataSource( data );
					break;
				}
				else {
					// Assuming that data is a collection of bean 
					// whose getter and setter methods match with the
					// report field values.
					source = new JRBeanCollectionDataSource( data );
				}
				break;
			}
		}
		return source;
	}
}