package Parsers;

import java.time.Duration;
import java.time.LocalDateTime;

import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import Objects.Product;

public class ElGiganten extends ParserBase {

	public void checkProduct(Product product) {
		ChromeDriver driver = getSeleniumDriver();

		driver.get(product.getUrl());
		WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
		try {
			wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(@data-ta,'productprice-text')]")));

			//
			WebElement findElement = driver.findElement(By.xpath("//span[contains(@data-ta,'productprice-text')]"));

			String priceValueString = findElement.getText();
			Float priceValue = formatPrice(priceValueString);
			float storedProductPrice = getStoredProductPrice(product);

			if ((storedProductPrice != -1 && priceValue < storedProductPrice) || storedProductPrice == -1) {
				product.setUpdatedDate(LocalDateTime.now());
				product.setPrice(priceValue);
				insertProduct(product);
			}
		} catch (TimeoutException e) {
			System.out.println("Failed to get " + product.getName() + " from " + product.getStore());
		}
		driver.close();
		driver.quit();
	}

}
