package Parsers;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
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 com.google.common.collect.Lists;

import Objects.Product;

public class Komplett extends ParserBase {

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

		driver.get(product.getUrl());
		WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
		wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("//div[@class='product-price']"), 0));
		//
		WebElement foundElement = driver.findElement(By.xpath("//div[@class='product-price']"));

		String dataObject = foundElement.getAttribute("data-initobject");

		ArrayList<String> objectParts = Lists.newArrayList(dataObject.split(","));
		List<String> list = objectParts.stream().filter(p -> String.valueOf(p.split(":")[0]).equals("\"priceNowRaw\"")).toList();

		float priceValue = -1;
		if (!list.isEmpty()) {
			String priceString = list.get(0).split(":")[1];
			priceValue = formatPrice(priceString);
		}
		float storedProductPrice = getStoredProductPrice(product);

		if ((storedProductPrice != -1 && priceValue < storedProductPrice) || storedProductPrice == -1) {
			product.setUpdatedDate(LocalDateTime.now());
			product.setPrice(priceValue);
			insertProduct(product);
		}

		driver.close();
		driver.quit();
	}

}
