package hsr.dsa;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import hsr.dsa.controller.ControllerManager;
import hsr.dsa.controller.RootNodeController;
import hsr.dsa.view.FXController;
import hsr.dsa.view.FXWindowManager;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

@SuppressWarnings("restriction")
public class MainApp extends Application implements FXWindowManager {
	private static final Logger log = LoggerFactory.getLogger(MainApp.class);
	
	private Stage stage;

	public static void main(String[] args) throws Exception {
		if(Arrays.asList(args).contains("noui")) {
			try (Scanner scanner = new Scanner(System.in)) {
				RootNodeController node = new RootNodeController();
				while (!scanner.nextLine().trim().equalsIgnoreCase("quit")) {
					Thread.yield();
				}
				node.stop();
			}
		} else {
			launch(args);
		}
	}

	public void start(Stage stage) throws Exception {
		this.stage = stage;

		log.info("Starting Hello JavaFX and Maven demonstration application");

		String fxmlFile = "/fxml/start.fxml";
		log.debug("Loading FXML for main view from: {}", fxmlFile);
		FXMLLoader loader = new FXMLLoader();
		Parent rootNode = (Parent) loader.load(getClass().getResourceAsStream(fxmlFile));
		((FXController)loader.getController()).setWindowManager(this);
		

		log.debug("Showing JFX scene");
		Scene scene = new Scene(rootNode);
		scene.getStylesheets().add("/styles/styles.css");

		this.stage.setTitle("Challenge Task");
		this.stage.setScene(scene);
		this.stage.show();
	}

	public void switchScene(String sceneLocation) {
		this.switchScene(sceneLocation, new HashMap<String, Object>());
	}

	@Override
	public void switchScene(String sceneLocation, Map<String, Object> paramater) {
		FXMLLoader loader = new FXMLLoader(getClass().getResource(sceneLocation));
		Parent root;
		try {
			root = (Parent) loader.load();
			((FXController)loader.getController()).setWindowManager(this);
			((FXController)loader.getController()).setParamater(paramater);
			
			Scene scene = new Scene(root);
			scene.getStylesheets().add("/styles/styles.css");
			
			this.stage.setScene(scene);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void stop() throws Exception {
		super.stop();
		ControllerManager.stop();
	}

	@Override
	public Stage getStage() {
		return this.stage;
	}
}
