package de.prob2.ui.beditor;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.regex.Matcher;

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

import com.google.inject.Inject;

import de.prob2.ui.internal.StageManager;
import javafx.fxml.FXML;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class BEditorStage extends Stage {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(BEditorStage.class);
	private static final Charset EDITOR_CHARSET = Charset.forName("UTF-8");
	
	@FXML
	private WebView beditor;
		
	private Path path;
	
	private WebEngine engine;
	
	private boolean loaded = false;
		
	@Inject
	public BEditorStage(final StageManager stageManager) {
		stageManager.loadFXML(this, "beditor.fxml");
		beditor.setContextMenuEnabled(false);
		engine = beditor.getEngine();
		engine.load(getClass().getResource("beditor.html").toExternalForm());
		engine.setJavaScriptEnabled(true);
	}
		
	@FXML
	public void handleSave() {
		saveFile(path);
	}
	
	@FXML
	public void handleSaveAs() {
		FileChooser fileChooser = new FileChooser();
		fileChooser.setTitle("Select Location");
		fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Classical B Files", "*.mch", "*.ref", "*.imp"));
		File openFile = fileChooser.showSaveDialog(this.getOwner());
		if (openFile != null) {
			File newFile = new File(openFile.getAbsolutePath() + (openFile.getName().contains(".") ? "" : ".mch"));
			saveFile(newFile.toPath());
			this.setTitle(newFile.getName());
			path = newFile.toPath();
		}
	}
	
	public void saveFile(Path path) {
		StandardOpenOption option = StandardOpenOption.CREATE;
		if(path.toFile().exists()) {
			option = StandardOpenOption.TRUNCATE_EXISTING;
		}
		try {
			String jscallCode = "editor.getValue()";
			String beditorText = engine.executeScript(jscallCode).toString();
			Files.write(path, beditorText.getBytes(EDITOR_CHARSET), option);
		} catch (IOException e) {
			LOGGER.error("File not found", e);
		}
	}
	
	@FXML
	public void handleClose() {
		this.close();
	}
	
	public void setTextEditor(String editor, Path path) {
		if(engine == null) {
			return;
		}
		this.loaded = true;
		this.path = path;
		editor = Matcher.quoteReplacement(editor);
		editor = editor.replaceAll("\\n", "\\\\n");
		String jscallCode = "editor.setValue('" + editor + "')";
		engine.executeScript(jscallCode);
	}
	
	public WebEngine getEngine() {
		return engine;
	}
	
	public boolean getLoaded() {
		return loaded;
	}
}

@@ -163,139 +163,8 @@
 ath;
-%0Aimport java.nio.file.StandardOpenOption;%0Aimport java.util.regex.Matcher;%0A%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aim
@@ -233,24 +233,25 @@
 ageManager;%0A
+%0A
 import javaf
@@ -263,16 +263,51 @@
 l.FXML;%0A
+import javafx.scene.control.Alert;%0A
 import j
@@ -427,16 +427,112 @@
 Stage;%0A%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Aimport netscape.javascript.JSObject;%0A%0A
 public c
@@ -759,16 +759,59 @@
 ditor;%0A%09
+%0A%09private final StageManager stageManager;%0A
 %09%0A%09priva
@@ -889,17 +889,16 @@
 false;%0A%09
-%09
 %0A%09@Injec
@@ -955,16 +955,52 @@
 ager) %7B%0A
+%09%09this.stageManager = stageManager;%0A
 %09%09stageM
@@ -1038,16 +1038,57 @@
 fxml%22);%0A
+%09%7D%0A%09%0A%09@FXML%0A%09private void initialize() %7B%0A
 %09%09bedito
@@ -1264,17 +1264,16 @@
 e);%0A%09%7D%0A%09
-%09
 %0A%09@FXML%0A
@@ -1914,266 +1914,137 @@
 %7B%0A%09%09
-StandardOpenOption option = StandardOpenOption.CREATE;%0A%09%09if(path.toFile().exists()) %7B%0A%09%09%09option = StandardOpenOption.TRUNCATE_EXISTING;%0A%09%09%7D%0A%09%09try %7B%0A%09%09%09String jscallCode = %22editor.getValue()%22;%0A%09%09%09String beditorText = engine.executeScript(jscallCode).toString(
+try %7B%0A%09%09%09final JSObject editor = (JSObject)engine.executeScript(%22editor%22);%0A%09%09%09String beditorText = (String)editor.call(%22getValue%22
 );%0A%09
@@ -2103,16 +2103,8 @@
 SET)
-, option
 );%0A%09
@@ -2151,26 +2151,125 @@
 or(%22
-File not found%22, e
+Could not save file%22, e);%0A%09%09%09stageManager.makeAlert(Alert.AlertType.ERROR, %22Could not save file:%5Cn%22 + e).showAndWait(
 );%0A%09
@@ -2367,22 +2367,20 @@
 (String 
-editor
+text
 , Path p
@@ -2390,16 +2390,17 @@
 ) %7B%0A%09%09if
+ 
 (engine 
@@ -2473,48 +2473,71 @@
 ;%0A%09%09
-editor = Matcher.quoteReplacemen
+final JSObject editor = (JSObject)engine.executeScrip
 t(
+%22
 editor
+%22
 );%0A%09
@@ -2547,138 +2547,30 @@
 itor
- = editor.replaceAll(%22%5C%5Cn%22, %22%5C%5C%5C%5Cn%22);%0A%09%09String jscallCode = %22editor.setValue('%22 + editor + %22')%22;%0A%09%09engine.executeScript(jscallCode
+.call(%22setValue%22, text
 );%0A%09

Improve error handling and text passing in BEditorStage