package me.coley.recaf;

import javax.swing.JOptionPane;

/**
 * Check if Recaf can be run on the current JVM.
 * 
 * <ul>
 * <li>Prevent execution on modularized JVM's until support is added</li>
 * <li>Verify compatible JavaFX</li>
 * </ul>
 * 
 * @author Matt
 */
public class DependencyChecks {

	public static boolean check() {
		double version = getVersion();
		if (version == 1.8) {
			return checkJFX();
		} else if (version > 1.8) {
			return true;
		} else {
			err("Outdated Java", "Please update java to the latest of Java 8 before using Recaf.");
			return false;
		}
	}

	private static boolean checkJFX() {
		String extra = "";
		if (!exists("javafx.application.Application$Parameters") || !exists("javafx.scene.control.MenuBar") || !exists(
				"javafx.scene.control.Menu")) {
			err("Mising JavaFX classes", "Could not load required JavaFX classes.\n" + extra);
			return false;
		}
		try {
			getClass("javafx.scene.control.MenuBar").getConstructor(getClass("[Ljavafx.scene.control.Menu;"));
		} catch (Exception e) {
			err("Mising JavaFX methods", "Could not load required JavaFX methods.\n" + extra);
			return false;
		}
		return true;
	}

	private static void err(String title, String msg) {
		System.err.println(msg);
		// If for some reason I'm still updating this past 2025, Swing is
		// supposed to be EOL March 2025.
		JOptionPane.showMessageDialog(null, msg, title, JOptionPane.ERROR_MESSAGE);
	}

	public static double getVersion() {
		String version = System.getProperty("java.version");
		int pos = version.indexOf('.');
		pos = version.indexOf('.', pos + 1);
		return Double.parseDouble(version.substring(0, pos));
	}

	private static boolean exists(String className) {
		try {
			getClass(className);
			return true;
		} catch (ClassNotFoundException e) {
			return false;
		}
	}

	private static Class<?> getClass(String className) throws ClassNotFoundException {
		return Class.forName(className, false, ClassLoader.getSystemClassLoader());
	}
}

@@ -375,32 +375,45 @@
 rsion == 1.8) %7B%0A
+%09%09%09// Java 8%0A
 %09%09%09return checkJ
@@ -418,16 +418,16 @@
 kJFX();%0A
-
 %09%09%7D else
@@ -444,24 +444,38 @@
 on %3E 1.8) %7B%0A
+%09%09%09// Java 9+%0A
 %09%09%09return tr
@@ -489,16 +489,30 @@
  else %7B%0A
+%09%09%09// Java 7-%0A
 %09%09%09err(%22
@@ -652,24 +652,24 @@
 heckJFX() %7B%0A
-
 %09%09String ext
@@ -677,16 +677,190 @@
 a = %22%22;%0A
+%09%09// Checking these classes because JavaFX used to be linked to the actual Java release.%0A%09%09// Some early versions of 1.8 are 'missing' these classes. So verify we have them.%0A
 %09%09if (!e
@@ -1762,16 +1762,72 @@
 f('.');%0A
+%09%09if (pos == -1)%0A%09%09%09return Double.parseDouble(version);%0A
 %09%09pos = 

Fix DependencyChecks failing in Java 9+ environments