package de.avatic.taricdb.helper.workbook;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import de.avatic.taricdb.helper.file.InMemFile;

public class ExcelTable {

	private ExcelTableType type;
	
	private InMemFile file;

	private XSSFWorkbook workbook;

	private XSSFSheet sheet;
	
	private int recordCount;

	private ExcelHeader header;
	
	public ExcelTable(ExcelTableType type, InMemFile file) throws IOException {
		this.file = file;		
		this.type = type;
		
		this.workbook = new XSSFWorkbook(new ByteArrayInputStream(file.getBlob()));
		this.sheet = getSheet();
		this.recordCount =	countRecords();
		
		this.header = new ExcelHeader(sheet.getRow(0));
	
	}
	
	private XSSFSheet getSheet() {
		if (type.getSheetIndex() == -1) {
			return workbook.getSheet(type.getSheetName());
		}
		
		return workbook.getSheetAt(type.getSheetIndex());
	}
	
	private int countRecords() {		
		if (sheet == null) {
			return -1;
		}
		return sheet.getPhysicalNumberOfRows();
	}



	public ExcelFileType getFileType() {
		return type.getFileType();
	}
	
	public ExcelTableType getType() {
		return type;
	}

	public List<ExcelRow> getRows() {
		ArrayList<ExcelRow> rows = new ArrayList<>();
				
		sheet.iterator().forEachRemaining(row -> {
			if (row.getRowNum() != 0) {
				rows.add(new ExcelRow(row , header));
			}			
		});
		
		return rows;
	}

	public int size() {
		return recordCount;
	}
	
}
