package dev.fyloz.trial.colorrecipesexplorer.xlsx.component;

import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.cells.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.util.*;

public class Sheet {

    private Document document;
    private XSSFSheet xsheet;

    private Map<Integer, XSSFRow> rows;
    private List<Cell> registeredCells;

    Sheet(Document document, XSSFSheet xsheet) {
        this.document = document;
        this.xsheet = xsheet;
        xsheet.setDefaultColumnWidth(xsheet.getDefaultColumnWidth() * 2);

        rows = new HashMap<>();
        registeredCells = new ArrayList<>();
    }

    public void registerCell(Cell cell) {
        registeredCells.add(cell);
    }

    public void registerAllCells(Collection<Cell> cells) {
        registeredCells.addAll(cells);
    }

    public List<Cell> getRegisteredCells() {
        return registeredCells;
    }

    public XSSFRow getRow(int rownum, boolean create) {
        int rowSize = rows.keySet().size();

        if (rowSize <= rownum) {
            if (!create) return null;

            for (int i = rowSize; i <= rownum; i++) {
                rows.put(i, xsheet.createRow(i));
            }
        }

        return rows.get(rownum);
    }

    public XSSFCell getCell(int rownum, int columnnum, CellType type, boolean create) {
        XSSFRow row = getRow(rownum, create);
//        List<XSSFCell> columns = rows.get(row);
        int columnsSize = row.getLastCellNum();

        if (columnsSize == -1) columnsSize = 0;

        if (columnsSize <= columnnum) {
            if (!create) return null;

            for (int i = columnsSize; i <= columnnum; i++) {
                row.createCell(i, type);
            }
        }

        return row.getCell(columnnum);
    }

    public XSSFCell getCell(Cell cell, int x, int y, boolean create) {
        return getCell(y, x, cell.getType(), create);
    }

    public XSSFSheet getXSheet() {
        return xsheet;
    }

    public Document getDocument() {
        return document;
    }

}
