package org.xbib.datastructures.xslx;

import javax.xml.stream.XMLStreamException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class XLSXWriterSupport extends WriterSupport {
	SimpleXLSXWorkbook workbook;

	public void open() {
		workbook = new SimpleXLSXWorkbook();
	}

	Sheet sheet;

	protected int getMaxRowNumOfSheet() {
		return Integer.MAX_VALUE / 2;
	}

	public void writeRow(String[] rowData) throws XMLStreamException, IOException {
		writeRow(rowData, null);
	}

	public void writeRow(String[] rowData, CellFormat[] formats) throws XMLStreamException, IOException {
		for (int col = 0; col < rowData.length; col++) {
			String string = rowData[col];
			if (string == null)
				continue;
			CellFormat format = null;
			if (formats != null) {
				for (CellFormat cellFormat : formats) {
					if (cellFormat != null && cellFormat.getCellIndex() == col) {
						format = cellFormat;
						break;
					}
				}
			}
			CellStyle cellStyle = null;
			if (format != null && (format.getBackColor() != -1 || format.getForeColor() != -1)) {
				Font font = null;
				Fill fill = null;
				if (format.getForeColor() != -1) {
					font = workbook.createFont();
					font.setColor(format.getForeColor());
				}
				if (format.getBackColor() != -1) {
					fill = workbook.createFill();
					fill.setFgColor(format.getBackColor());
				}
				cellStyle = workbook.createStyle(font, fill);
			}
			sheet.modify(rowpos, col, string, cellStyle);
		}
	}

	public void close() {
		if (workbook == null)
			return;
		OutputStream fos = null;
		try {
			if (file != null) {
				fos = new FileOutputStream(file);
			} else if (output != null) {
				fos = output;
			} else {
				throw new IllegalStateException("no output specified");
			}
			workbook.commit(fos);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					//
				}
			}
			if (workbook != null)
				workbook.close();
		}
	}

	public void createNewSheet() throws IOException {
		if (sheetIndex > 0) {
			throw new IllegalStateException("only one sheet allowed");
		}
		sheet = workbook.getSheet(sheetIndex, true);
	}
}
