package com.playwrightdemo.utils;

import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class ExcelUtilities {

    private static FileInputStream fis;

    private static XSSFWorkbook workBook;

    private static XSSFSheet sheet;

    private static XSSFRow row;

    private static XSSFRow col;

    private static XSSFCell cell;

    private static String excelFilePath = "src/main/java/com/playwrightdemo/testdata/Excellence Login Data.xlsx";

    private static String sheet_name = "userData";


    public ExcelUtilities() throws IOException {

        fis = new FileInputStream(new File (excelFilePath));
        workBook = new XSSFWorkbook(fis);
        sheet = workBook.getSheet(sheet_name);
        fis.close();


    }


    public static String[][] getCellData() {

        int noOfRows = sheet.getPhysicalNumberOfRows();
        int noOfCols = sheet.getRow(0).getLastCellNum();

        String[][] data = new String[noOfRows - 1][noOfCols];

        for (int i = 1; i <= noOfRows - 1; i++) {

            for (int j = 0; j < noOfCols; j++) {

                DataFormatter df = new DataFormatter();
                data[i - 1][j] = df.formatCellValue(sheet.getRow(i).getCell(j));

            }

        }

        return data;
    }

    public void setCellData(String value,int rowNum, int colNum) throws IOException {

        row=sheet.getRow(rowNum);
        cell=row.getCell(colNum);

        if (cell==null){

            cell=row.createCell(colNum);
            cell.setCellValue(value);

        }

        else {

            cell.setCellValue(value);

        }

        FileOutputStream fileOut=new FileOutputStream("src/main/java/com/playwrightdemo/testdata/ExcelWriterData.xlsx");

        workBook.write(fileOut);

        fileOut.flush();
        fileOut.close();

    }


}
