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

import dev.fyloz.trial.colorrecipesexplorer.xlsx.component.Sheet;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

public class CellUtils {
    public static XSSFColor getXSSFColor(int[] rgb) {
        return new XSSFColor(new byte[]{(byte) rgb[0], (byte) rgb[1], (byte) rgb[2]}, new DefaultIndexedColorMap());
    }

    public static boolean isCellEmpty(Sheet sheet, int x, int y) {
        XSSFRow row = sheet.getRow(y, false);

        if (row == null) {
            return true;
        }

        XSSFCell cell = row.getCell(x);

        if (cell == null) { // use row.getCell(x, Row.CREATE_NULL_AS_BLANK) to avoid null cells
            return true;
        }

        if (cell.getCellType() == CellType.BLANK) {
            return true;
        }

        if (cell.getCellType() == CellType.STRING && cell.getStringCellValue().trim().isEmpty()) {
            return true;
        }

        return false;
    }

    public static boolean isCellInMergedCell(Sheet sheet, int x, int y) {
        XSSFSheet xsheet = sheet.getXSheet();

        int numberOfMergedRegions = xsheet.getNumMergedRegions();

        for (int i = 0; i < numberOfMergedRegions; i++) {
            CellRangeAddress mergedCell = xsheet.getMergedRegion(i);

            if (mergedCell.isInRange(y, x)) {
                return true;
            }
        }

        return false;
    }
}
