/**
 * 
 */
package org.springblade.etl.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

/**
 * @author wookvn
 *
 */
public class CubeExcelAnalysisEventListener extends AnalysisEventListener<Map<Integer, String>> {

	private int limit;
	private boolean readAll;
	private Consumer<List<Map<Integer, String>>> consumer;
	private Map<Integer, String> headMap = new HashMap<Integer, String>();
	
	private List<Map<Integer, String>> dataList = new ArrayList<Map<Integer,String>>();
	
	
	/**
	 * @param limit
	 * @param readAll
	 * @param consumer
	 */
	public CubeExcelAnalysisEventListener(int limit, boolean readAll, Consumer<List<Map<Integer, String>>> consumer) {
		super();
		this.limit = limit;
		this.readAll = readAll;
		this.consumer = consumer;
	}

	public CubeExcelAnalysisEventListener(int limit, Consumer<List<Map<Integer, String>>> consumer) {
		super();
		this.limit = limit;
		this.readAll = true;
		this.consumer = consumer;
	}
	
	public CubeExcelAnalysisEventListener(Consumer<List<Map<Integer, String>>> consumer) {
		super();
		this.readAll = true;
		this.consumer = consumer;
	}
	
	@Override
	public void invoke(Map<Integer, String> data, AnalysisContext context) {
		dataList.add(data);
		if(limit > 0 && dataList.size() >= limit) {
			consumer.accept(dataList);
			if(!readAll) {
				throw new ExcelReadLimitException("ReadExcel finished|limit:" + limit);
			}else {
				dataList.clear();
			}
		}
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		consumer.accept(dataList);
	}
	
	@Override
	public void invokeHeadMap(Map<Integer, String> headData, AnalysisContext context) {
		headMap.putAll(headData);
	}

	public Map<Integer, String> getHeadMap() {
		return headMap;
	}
	
	public List<Map<Integer, String>> getDataList() {
		return dataList;
	}
}
