package zacksolutions;

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.interactions.Actions;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

public class AmazonQuestion {
  public static WebDriver driver;
  public static String[] items = { "Brocolli", "Beetroot", "Beans", "Carrot", "Potato" };
  public static String code = "";

  public static void main(String[] args) {
  }

  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/seleniumPractise/";
    driver.get(url);
    try {
      getItems();
      checkOut();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      driver.close();
    }

  }

  public static void checkOut() {
    driver.findElement(By.xpath("//a[@class='cart-icon']/img")).click();
    driver.findElement(By.xpath("//div[@class='action-block']/button")).click();
    driver.findElement(By.cssSelector(".promoCode")).sendKeys("rahulshettyacademy");
    driver.findElement(By.cssSelector(".promoBtn")).click();
    code = driver.findElement(By.cssSelector(".promoInfo")).getText();
    System.out.println(code);
  }

  public static void getItems() throws InterruptedException {
    List<WebElement> itemsName = driver.findElements(By.cssSelector("h4[class$='product-name']"));
    List<String> listOfItems = Arrays.asList(items);
    int lastItem = 0;
    for (int i = 0; i < itemsName.size(); i++) {
      String item = itemsName.get(i).getText().split(" - ")[0].trim();
      if (listOfItems.contains(item)) {
        driver.findElements(By.xpath("//div[@class='product-action']/button")).get(i).click();
        lastItem++;
        if (lastItem == listOfItems.size()) {
          break;
        }
      }
    }
  }
}
