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

import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.Document;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.Sheet;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.cells.Cell;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.cells.styles.IBiggerCell;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.exception.InvalidCellTypeException;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.util.CellUtils;
import org.apache.poi.ss.util.CellRangeAddress;

public class SheetBuilder {

    private Sheet sheet;
    private Iterable<Cell> cells;

    public SheetBuilder(Sheet sheet) {
        this.sheet = sheet;

        cells = sheet.getRegisteredCells();
    }

    private void applyCellMerge(IBiggerCell cell, int x, int y) {
        int width = cell.getWidth() - 1;
        int height = cell.getHeight() - 1;

        sheet.getXSheet().addMergedRegion(new CellRangeAddress(y, y + height, x, x + width));
    }

    public void build() throws InvalidCellTypeException {
        int x = 0;
        int y = 0;

        for (Cell cell : cells) {
            while (!CellUtils.isCellEmpty(sheet, x, y) || CellUtils.isCellInMergedCell(sheet, x, y)) {
                x++;

                if (x >= Document.WIDTH) {
                    x = 0;
                    y++;
                }
            }

            new CellBuilder(sheet.getDocument(), cell, x, y).build();
            if (cell instanceof IBiggerCell) {
                IBiggerCell biggerCell = (IBiggerCell) cell;

                applyCellMerge(biggerCell, x, y);

                x += biggerCell.getWidth() - 1;
            } else {
                x++;
            }

            if (x >= Document.WIDTH) {
                x = 0;
                y++;
            }
        }
    }
}
