package com.agile611.testng.webdriver;

import java.time.Duration;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;

public class AlertsTest extends BaseTest {

    public void acceptAlert() {
        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(2));
            wait.until(ExpectedConditions.alertIsPresent());
            Alert alert = driver.switchTo().alert();
            alert.accept();
        } catch (Exception e) {
            //exception handling
        }
    }

    public void dismissAlert() {
        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(2));
            wait.until(ExpectedConditions.alertIsPresent());
            Alert alert = driver.switchTo().alert();
            alert.dismiss();
        } catch (Exception e) {
            //exception handling
        }
    }

    public void promptAlert() {
        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(2));
            wait.until(ExpectedConditions.alertIsPresent());
            Alert alert = driver.switchTo().alert();
            alert.sendKeys("Hola hola super hola");
            alert.accept();
        } catch (Exception e) {
            //exception handling
        }
    }


    @Test
    public void testApp() throws InterruptedException {
        driver.navigate().to("https://the-internet.herokuapp.com/javascript_alerts");
        WebElement resultBanner = driver.findElement(By.id("result"));
        driver.findElement(By.xpath(".//*[@id='content']/div/ul/li[1]/button")).click();
        Thread.sleep(2000);
        acceptAlert();
        Thread.sleep(2000);
        Assert.assertEquals(resultBanner.getText(), "You successfully clicked an alert");
        driver.findElement(By.xpath(".//*[@id='content']/div/ul/li[2]/button")).click();
        Thread.sleep(2000);
        acceptAlert();
        Thread.sleep(2000);
        Assert.assertEquals(resultBanner.getText(), "You clicked: Ok");
        driver.findElement(By.xpath(".//*[@id='content']/div/ul/li[2]/button")).click();
        Thread.sleep(2000);
        dismissAlert();
        Thread.sleep(2000);
        Assert.assertEquals(resultBanner.getText(), "You clicked: Cancel");
        driver.findElement(By.xpath(".//*[@id='content']/div/ul/li[3]/button")).click();
        Thread.sleep(2000);
        promptAlert();
        Thread.sleep(2000);
        Assert.assertEquals(resultBanner.getText(), "You entered: Hola hola super hola");
    }
}
