package com.agile611.testng.webdriver;

import java.time.Duration;
import java.util.Set;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class MultipleWindowsTest extends BaseTest {

    @Test
    public void multipleWindows() throws InterruptedException {
        driver.get("http://the-internet.herokuapp.com/windows");

        String originalWindow = driver.getWindowHandle();

        driver.findElement(By.xpath("//a[@href=\'/windows/new\']")).click();

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
        Thread.sleep(3000); // Temas del Firefox
        wait.until(ExpectedConditions.numberOfWindowsToBe(2));
        // numberOfWindowsToBe de Firefox no se interpreta bien, por eso el sleep

        String newWindow = "";
        for (String handle : driver.getWindowHandles()) {
            System.out.println(handle);
            if (!handle.equals(originalWindow)) {
                newWindow = handle;
            }
        }

        // Verificar ventana original
        driver.switchTo().window(originalWindow);
        assertThat(driver.getTitle(), is(not(equalTo("New Window"))));

        // Verificar nueva ventana
        driver.switchTo().window(newWindow);
        assertThat(driver.getTitle(), is(equalTo("New Window")));

        // ✅ Cerrar la ventana nueva y volver a la original
        driver.close();
        driver.switchTo().window(originalWindow);
    }

    @Test(dependsOnMethods = "multipleWindows")
    public void multipleWindowsRedux() throws InterruptedException {
        driver.get("http://the-internet.herokuapp.com/windows");

        String firstWindow = driver.getWindowHandle();
        String newWindow = "";

        driver.findElement(By.cssSelector(".example a")).click();

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
        Thread.sleep(3000); // Temas de tiempos del Firefox
        wait.until(ExpectedConditions.numberOfWindowsToBe(2));
        // numberOfWindowsToBe de Firefox no se interpreta bien, por eso el sleep

        Set<String> allWindows = driver.getWindowHandles();

        for (String window : allWindows) {
            System.out.println(window);
            if (!window.equals(firstWindow)) {
                newWindow = window;
            }
        }

        driver.switchTo().window(firstWindow);
        assertThat(driver.getTitle(), is(not(equalTo("New Window"))));

        driver.switchTo().window(newWindow);
        assertThat(driver.getTitle(), is(equalTo("New Window")));

        // ✅ Cerrar la ventana nueva y volver a la original
        driver.close();
        driver.switchTo().window(firstWindow);
    }
}