package parser;

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

import javax.imageio.ImageIO;

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

import obejcts.Recepie;

public class Svenskarecept extends ParserBase {

	public static final String BASE_URL = "https://svenskarecept.se/";

	public static final String RECEPIE_TITLE_XPATH = "//div[@class='entry-grid hgrid']//h2";
	public static final String RECEPIELIST_ITEMS_XPATH = "//div[@class='entry-grid hgrid']";
	public static final String PATH_SEPARATOR = "+";
	public static final String URL_SEARCH_PATTERN = "?s=";
	public static final String COOKIE_CONSENT_BUTTON_XPATH = "NA";
	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) {

	}

	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();
		}
	}
}
