package de.siphalor.was.visual.jfx.util;

import de.siphalor.was.assets.AssetsManager;
import de.siphalor.was.content.lang.I18n;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;

import java.io.IOException;

public class JFXUtil {
	public static Image scaleTo(Image image, int width) {
		double scale = image.getWidth() / (double) width;
		int height = (int) (image.getHeight() / scale);

		WritableImage res = new WritableImage(width, height);
		PixelReader reader = image.getPixelReader();
		PixelWriter writer = res.getPixelWriter();

		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				writer.setColor(x, y, reader.getColor((int) (x * scale), (int) (y * scale)));
			}
		}

		return res;
	}

	public static void setStyleClass(Node node, String clazz, boolean active) {
		if (active) {
			if (!node.getStyleClass().contains(clazz)) {
				node.getStyleClass().add(clazz);
			}
		} else {
			node.getStyleClass().remove(clazz);
		}
	}

	public static Scene loadScene(String fxml, Object controller, I18n i18n) {
		FXMLLoader loader = new FXMLLoader();
		loader.setResources(i18n);
		loader.setController(controller);
		Parent parent = null;
		try {
			parent = loader.load(AssetsManager.getStream("jfx/" + fxml + ".fxml").orElseThrow());
		} catch (IOException e) {
			e.printStackTrace();
		}
		Scene scene = new Scene(parent);
		scene.getStylesheets().add("assets/jfx/main.css");
		return scene;
	}
}
