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

import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.Document;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.cells.Cell;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.cells.styles.IColoredCell;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.cells.styles.IFontCell;
import dev.fyloz.trial.colorrecipesexplorer.xlsx.exception.InvalidCellTypeException;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;

public class CellBuilder {

    private Document document;
    private Cell cell;
    private XSSFCell xcell;

    public CellBuilder(Document document, Cell cell, int x, int y) {
        this.document = document;
        this.cell = cell;

        xcell = document.getSheet().getCell(cell, x, y, true);
    }

    private void applyColor(IColoredCell cell, XSSFCellStyle style) {
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(cell.getBackgroundColor().getIndex());
    }

    private void applyFont(IFontCell cell, XSSFCellStyle style) {
        XSSFFont font = document.createFont();
        font.setBold(cell.isBold());
        font.setColor(cell.getFontColor().getIndex());
        font.setFontHeightInPoints(cell.getFontHeight());

        style.setFont(font);
        if (cell.isCentered()) style.setAlignment(HorizontalAlignment.CENTER);
    }

    private void applyStyle() {
        XSSFCellStyle style = document.createCellStyle();
        style.setWrapText(true);

        if (cell instanceof IColoredCell) applyColor((IColoredCell) cell, style);
        if (cell instanceof IFontCell) applyFont((IFontCell) cell, style);

        xcell.setCellStyle(style);
    }

    private void applyContent() throws InvalidCellTypeException {
        switch (cell.getType()) {
            case STRING:
                xcell.setCellValue(cell.getContentText());
                break;
            case NUMERIC:
                xcell.setCellValue(cell.getContentNum());
                break;
            default:
                throw new InvalidCellTypeException(cell.getType());
        }
    }

    public void build() throws InvalidCellTypeException {
        applyStyle();
        applyContent();
    }
}
