package DataProvider;


import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;

public class DataProviderfromExcel {

    WebDriver obj = new FirefoxDriver();
    WebDriverWait wait = new WebDriverWait(obj, Duration.ofSeconds(20));

    @BeforeClass
    void setup() {

        obj.get("https://rahulshettyacademy.com/locatorspractice/");
        obj.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
    }

    @Test(dataProvider = "dataStorage")
    void LoginTest(String username, String password)
    {
        WebElement usernameField = obj.findElement(By.id("inputUsername"));

        wait.until(ExpectedConditions.visibilityOf(usernameField));
        usernameField.sendKeys(username);
        usernameField.clear();

        WebElement passwordField = obj.findElement(By.xpath("//input[@placeholder='Password']"));
        passwordField.sendKeys(password);
        usernameField.clear();

        obj.findElement(By.className("submit")).click();

    }

    @DataProvider(name = "dataStorage")
    public Object[][] dataStorage() throws IOException
    {
        String filePath = "//Users//zain//Documents//dataproviderfile.xlsx";
        FileInputStream fileInputStream = new FileInputStream(filePath);

        // Load workbook and sheet
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);

        int rows = sheet.getPhysicalNumberOfRows();
        int cols = sheet.getRow(0).getPhysicalNumberOfCells();
        Object[][] data = new Object[rows - 1][cols];

        for (int i = 1; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                data[i - 1][j] = sheet.getRow(i).getCell(j).toString();
            }
        }

        workbook.close();
        fileInputStream.close();
        return data;
    }

    @AfterClass
    void Exit() {
        obj.quit();
    }
}
