package eu.simstadt.regionchooser;

import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Paths;
import java.util.concurrent.TimeoutException;
import java.util.prefs.Preferences;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
import javafx.application.Platform;
import javafx.stage.Stage;


@ExtendWith(ApplicationExtension.class)
class RegionChooserGUITest
{
	private static final String TEST_REPOSITORY_PATH = Paths.get("../../TestRepository").toAbsolutePath().toString();
	private static String originalRepository;
	private static Preferences userPrefs = Preferences.userRoot().node("/eu/simstadt/desktop");

	private FxRobot robot;

	@BeforeAll
	/**
	 * This method makes sure that the JavaFX/TestFX tests are run in headless mode. They should work on Linux Server,
	 * thanks to https://github.com/TestFX/Monocle
	 *
	 * Alternatively, in order to force headless mode from Maven:
	 *
	 * mvn clean package -Dtestfx.robot=glass -Dtestfx.headless=true -Dprism.order=sw -Dprism.text=t2k
	 *
	 * More info:
	 *
	 * https://stackoverflow.com/questions/27403410/headless-testing-with-javafx-and-testfx
	 * https://medium.com/@danielnenkov/run-testfx-tests-on-jenkins-running-on-ec2-d68197e10e2b
	 */
	private static void setupHeadlessTests() {
		//		System.setProperty("testfx.robot", "glass");
		//		System.setProperty("testfx.headless", "true");
		//		System.setProperty("prism.order", "sw");
		//		System.setProperty("prism.text", "t2k");
	}

	@BeforeAll
	private static void setRepositoryToTestRepository() {
		originalRepository = userPrefs.get("RECENT_REPOSITORY", TEST_REPOSITORY_PATH);
		userPrefs.put("RECENT_REPOSITORY", TEST_REPOSITORY_PATH);
	}

	@AfterAll
	private static void resetRepositoryToOriginalRepository() {
		userPrefs.put("RECENT_REPOSITORY", originalRepository);
	}

	/**
	 * Will be called with {@code @Before} semantics, i. e. before each test method.
	 *
	 * @param stage - Will be injected by the test runner.
	 */
	@Start
	private void start(Stage stage) {
		Platform.runLater(() -> new RegionChooserFX().start(stage));
	}

	/**
	 * @param robot - Will be injected by the test runner.
	 * @throws InterruptedException
	 * @throws TimeoutException
	 */
	@Test
	void testClickOnRegionChooser(FxRobot testRobot) throws InterruptedException, TimeoutException {
		this.robot = testRobot;
		System.out.println(robot.window(0).getScene());
		System.out.println(robot.lookup("#RegionChooserBrowser").query());
		//		WaitForAsyncUtils.waitFor(30, TimeUnit.SECONDS, () -> !runButton.isDisabled());
		robot.clickOn("TEST");
		assertTrue(false);
	}
}
