package cn.myapps.runtime.report.model;


import net.sf.dynamicreports.report.constant.Constants;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JRRewindableDataSource;

import java.io.Serializable;
import java.util.*;

/**
 * 重写此类为了自定义数据源能获取到drDataSource的列信息
 * <p>DRDataSource class.</p>
 *
 * @author Ricardo Mariaca (r.mariaca@dynamicreports.org)
 * @version $Id: $Id
 */
public class DRDataSource implements JRRewindableDataSource, Serializable {
    private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;

    private String[] columns;
    private List<Map<String, Object>> values;
    private Iterator<Map<String, Object>> iterator;
    private Map<String, Object> currentRecord;

    /**
     * <p>Constructor for DRDataSource.</p>
     *
     * @param columns a {@link java.lang.String} object.
     */
    public DRDataSource(String... columns) {
        this.columns = columns;
        this.values = new ArrayList<Map<String, Object>>();
    }

    /**
     * <p>add.</p>
     *
     * @param values a {@link java.lang.Object} object.
     */
    public void add(Object... values) {
        Map<String, Object> row = new LinkedHashMap<String, Object>();
        for (int i = 0; i < values.length; i++) {
            row.put(columns[i], values[i]);
        }
        this.values.add(row);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object getFieldValue(JRField field) throws JRException {
        return currentRecord.get(field.getName());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean next() throws JRException {
        if (iterator == null) {
            this.iterator = values.iterator();
        }
        boolean hasNext = iterator.hasNext();
        if (hasNext) {
            currentRecord = iterator.next();
        }
        return hasNext;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void moveFirst() throws JRException {
        iterator = null;
    }

    public String[] getColumns() {
        return columns;
    }

    public List<Map<String, Object>> getValues() {
        return values;
    }

    public Map<String, Object> getCurrentRecord() {
        return currentRecord;
    }
}
