package parser;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import obejcts.Recepie;

public class Kokaihop extends ParserBase {

	public static final String BASE_URL = "https://www.kokaihop.se/recept-sok?type=Recipe&fetchFacets=true&sort=relevence&withImages=true";
	public static final String PATH_SEPARATOR = "%20";
	public static final String URL_SEARCH_PATTERN = "&q=";

	public static final String RECEPIE_TITLE_XPATH = ".//h2/a";
	public static final String RECEPIELIST_ITEMS_XPATH = "//div[@class='recipe-container']/*";
	public static final String COOKIE_CONSENT_BUTTON_XPATH = "//button[@mode='primary']";
	public static final String IMAGE_XPATH = "";

	public static final String SHOW_MORE_XPATH = "";

	public static boolean isFromHereRecepie(String url) {
		return url.contains(BASE_URL);
	}

	@Override protected void parseRecepie(WebElement recepie, String recepieTitle) {
		String description = driver.findElement(By.xpath("//div[@id='recipeDetailInfo']/div/p/span")).getText();

		Recepie newRecepie = new Recepie();
		newRecepie.setDescription(description);
		newRecepie.setUrl(driver.getCurrentUrl());
		newRecepie.setName(recepieTitle);

		newRecepie.setId(database.insertRecepie(newRecepie));

		List<WebElement> ingredients = driver.findElements(By.xpath("//div[@class='ingredients_section']/ul/li"));

		for (WebElement ingredient : ingredients) {
			// NOT DONE, Kind of annoying to parse
			// https://www.kokaihop.se/recept/kyckling-gryta-4
		}
	}

	void saveImage(Recepie newRecepie) {
		WebElement imageElement = driver.findElement(By.xpath(IMAGE_XPATH));
		String imgSrc = imageElement.getAttribute("currentSrc");

		try {
			if (imgSrc.contains(".webp")) {
				imgSrc = imgSrc.replace(".webp", "");
			}
			URL imageUrl = new URL(imgSrc);
			BufferedImage savedImage = ImageIO.read(imageUrl);

			BufferedImage resizedImage = Scalr.resize(savedImage, 300);

			File file = new File("recepie-image.png");
			ImageIO.write(resizedImage, "png", file);

			database.saveRecepieImage(newRecepie.getId(), file);

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
