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 org.openqa.selenium.support.ui.ExpectedConditions;

import obejcts.Ingredient;
import obejcts.Recepie;

public class Ica extends ParserBase {

	public static final String BASE_URL = "https://www.ica.se/recept";
	public static final String PATH_SEPARATOR = "+";
	public static final String RECEPIELIST_ITEMS_XPATH = "//div[contains(@class,'grid-items')]";
	public static final String SHOW_MORE_XPATH = "//div[contains(@class,'show-more-button')]";
	public static final String RECEPIE_TITLE_XPATH = ".//a[contains(@class,'recipe-card__content__title')]";
	public static final String URL_SEARCH_PATTERN = "?q=";
	public static final String COOKIE_CONSENT_BUTTON_XPATH = "//button[@id='onetrust-accept-btn-handler']";
	public static final String IMAGE_XPATH = "//img[contains(@class,'recipe-header__image') and contains(@class,'image-loaded')]";

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

	@Override protected void parseRecepie(WebElement recepie, String recepieTitle) {
		scrollElementIntoViewCenter(driver, recepie);
		wait.until(ExpectedConditions.elementToBeClickable(recepie));
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		recepie.click();

		Recepie newRecepie = new Recepie();

		String titleXpath = "//h1[contains(@class,'recipe-header__title')]";
		String recepieDetailsXpath = "//a[@class='items']";
		String ingredientXpath = "//div[@class='ingredients-list-group__card']";
		String stepByStepXpath = "//label[contains(@class, 'cooking-steps-main')]";

		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath(titleXpath), 0));
		newRecepie.setName(driver.findElement(By.xpath(titleXpath)).getText());
		List<WebElement> details = driver.findElements(By.xpath(recepieDetailsXpath));

		newRecepie.setTime(details.get(0).getText().replaceAll("[^0-9]", ""));
		if (details.size() > 2) {
			newRecepie.setDifficulty(details.get(2).getText());
		}

		newRecepie.setDescription(driver.findElement(By.xpath("//div[@class='recipe-header__preamble']//p")).getText());
		newRecepie.setUrl(driver.getCurrentUrl());

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

		List<WebElement> ingredients = driver.findElements(By.xpath(ingredientXpath));

		for (WebElement ingredient : ingredients) {
			String amount = "";
			String measurement = "";
			if (checkIfElementExists(ingredient, ".//span[@class='ingredients-list-group__card__qty']")) {
				WebElement measure = ingredient.findElement(By.xpath(".//span[@class='ingredients-list-group__card__qty']"));
				amount = getAmountFromText(measure.getText());
				measurement = measure.getText().replaceAll("[0-9]", "").trim();
			}
			WebElement ingr = ingredient.findElement(By.xpath(".//span[@class='ingredients-list-group__card__ingr']"));

			database.addIngredientToRecepie(newRecepie.getId(), new Ingredient(fixName(ingr.getText()), amount, measurement));
		}

		List<WebElement> steps = driver.findElements(By.xpath(stepByStepXpath));

		int stepCounter = 1;
		for (WebElement step : steps) {
			String stepDesc = step.getText();

			database.addRecepieStep(newRecepie.getId(), stepCounter++, stepDesc);
		}

		saveImage(newRecepie);

		driver.navigate().back();
	}

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