/**
 * Moxkiriya standalone Wiki.
 * Wiki preview window controller.
 * 
 * @author Ryuhei Terada
 * See the '<a href="{@docRoot}/copyright.html">Copyright</a>'
 */
package com.wiki.standalone.moxkiriya;

import java.net.URL;
import java.util.HashMap;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.web.WebView;

/**
 * Controll preview window.
 *
 */
public class WikiPreviewWindowController implements Initializable {
	/** Wiki engine */
	private WikiEngine wikiEngine_;

	/** Wiki preview window */
	private WikiPreviewWindow wikiPreviewWindow_;

	@FXML private Button   buttonReload;
	@FXML private Button   buttonClose;
	@FXML private WebView  webView;
	
	@Override
	public void initialize(URL url, ResourceBundle resource) {
		wikiEngine_ = new WikiEngine();
	}

	/**
	 * WikiPreviewWindow setter.
	 */
	public void setWikiPreviewWindow(WikiPreviewWindow previewWindow) {
		wikiPreviewWindow_ = previewWindow;
	}

	/**
	 * Wiki repository setter.
	 * @param wikiRepository
	 */
	public void setWikiRepository(WikiRepository wikiRepository) {
		wikiEngine_.setWikiRepository(wikiRepository);
	}

	/**
	 * Wiki content loader.
	 * @param pageData
	 */
	public void loadWikiContent(PageData pageData) {
		try {
			HashMap<String, PageData> map = new HashMap<String, PageData>();
			map.put("preview", pageData);
			wikiEngine_.setPageDataMap(map);

			String content = wikiEngine_.parse(pageData);
			webView.getEngine().loadContent(content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@FXML
	public void onActionButtonReload(ActionEvent event) {
		try {
			PageData pageData = wikiPreviewWindow_.getLatestContents();
			loadWikiContent(pageData);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@FXML
	public void onActionButtonClose(ActionEvent event) {
		((Node)event.getSource()).getScene().getWindow().hide();
	}
}
