package zacksolutions;

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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 * SwitchWin
 */
public class SwitchWin {

  public static WebDriver driver;
  public static String email = "";

  public static void main(String[] args) throws InterruptedException {

    Initialize();
  }

  public static void Initialize() throws InterruptedException {
    System.setProperty("web-driver.gecko.driver", "user.dir" + "LearnSelenium/DemoProject/drivers/geckodriver");
    driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    String url = "https://rahulshettyacademy.com/loginpagePractise/#";
    driver.get(url);
    try {
      loginPage();
      userInput();
    } finally {
      Thread.sleep(6000);
      driver.quit();
    }
  }

  public static void loginPage() throws InterruptedException {
    driver.findElement(By.cssSelector(".blinkingText")).click();
    Set<String> tabs = driver.getWindowHandles();
    Iterator<String> it = tabs.iterator();
    String parentTab = it.next();
    String childTab = it.next();
    driver.switchTo().window(childTab);
    String []phrase = driver.findElement(By.cssSelector(".im-para.red")).getText().split(" ");
    for (int i = 0; i < phrase.length; i++) {
      if(phrase[i].contains("@")){
        email = phrase[i].trim();
      }
    }
    System.out.println("Please use the followoing email: " + email);
    driver.switchTo().window(parentTab);
  }
  public static void userInput() throws InterruptedException {
    driver.findElement(By.cssSelector("#username")).sendKeys("rahulshettyacademy");
    driver.findElement(By.cssSelector("#password")).sendKeys("learning");
    driver.findElement(By.xpath("//label[2]//span[2]")).click();
    driver.findElement(By.cssSelector(".btn.btn-success")).click();
    driver.findElement(By.xpath("//input[@id='terms']")).click();
    driver.findElement((By.cssSelector(".btn.btn-info.btn-md"))).click();
    System.out.println(driver.getTitle());
  }
}
