/**
 * Moxkiriya standalone Wiki.
 * Wiki main window.
 * 
 * @author Ryuhei Terada
 * See the '<a href="{@docRoot}/copyright.html">Copyright</a>'
 */

package com.wiki.standalone.moxkiriya;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.ResourceBundle;

import com.wiki.standalone.moxkiriya.util.FileIO;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 * Application Main.
 * 
 *
 */
public class WikiMainWindow {
	/** primary stage. */
	private Stage primaryStage_ = null;

	/** Resource Bundle */
	private ResourceBundle resources_ = null;

	/** Setting Manager */
	private SettingManager settingManager_ = null;

	/** WikiEngine */
	private WikiEngine wikiEngine_;
	
	/** Window Controller */
	private WikiMainWindowController controller_;

	public enum CloseType {
		EXIT,
		RESTART
	};
	
	/**
	 * Constructor.
	 */
	public WikiMainWindow(Stage primaryStage, ResourceBundle resources) {
		primaryStage_   = primaryStage;
		resources_      = resources;
		settingManager_ = SettingManager.getInstance();
	}

	/**
	 * Show WikiMainWindow
	 * @throws Exception
	 */
	public CloseType show() throws Exception {
		try {
			FXMLLoader loader = new FXMLLoader(getClass().getResource("WikiMainWindow.fxml"), resources_);
			loader.load();

			controller_ = loader.getController();
			controller_.setWikiEngine(wikiEngine_);

			Scene scene  = new Scene((Parent)loader.getRoot());
			scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

			wikiEngine_.setPageDataMap(WikiEngine.MAINPAGE_TITLE);
			controller_.loadWikiContent();

			Stage stage  = new Stage(StageStyle.DECORATED);
			stage.initOwner(primaryStage_);
			controller_.setStage(stage);

			stage.setScene(scene);
			stage.setTitle(resources_.getString("key.Application.Title"));
			stage.showAndWait();

			controller_.hidePreviewWindow();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return controller_.getCloseType();
	}
	/**
	 * Wikiのメインページのディレクトリツリーを構築する。
	 * @param wikirootPath
	 * @throws Exception 
	 */
	public void buildWikiMainTree(File wikirootPath) throws Exception {
		createCssFiles();

		uploadResourcefile(settingManager_.getAbsolutePath(WikiEngine.FIXED_STYLESHEET_FILENAME),
				WikiEngine.FIXED_STYLESHEET_FILENAME);

		uploadResourcefile(settingManager_.getAbsolutePath(WikiEngine.DEFAULT_STYLESHEET_FILENAME),
				WikiEngine.DEFAULT_STYLESHEET_FILENAME);

		createRepositoryConfig();
		wikiEngine_ = new WikiEngine();
		wikiEngine_.buildWikiRepository(wikirootPath);
	}
	
	/**
	 * styleシートをコピーする
	 * @param absolutePath
	 * @param filename
	 * @throws IOException 
	 */
	public void uploadResourcefile(String absolutePath, String filename) throws IOException {
		File destFile   = new File(absolutePath);

		if (destFile.exists() != true) {
			InputStream in       = getClass().getResourceAsStream("resources/" + filename);
			Path        destPath = Paths.get(absolutePath);
			Files.createDirectories(destPath.getParent());
			Files.copy(in, destPath);
		}
	}

	/**
	 * Create Repository.xml
	 * @throws Exception
	 */
	private void createRepositoryConfig() throws Exception {
		SettingManager settingMgr     = SettingManager.getInstance();
		String         path           = settingMgr.get(SettingManager.SETTINGSKEY_MOXKIRIYA_USER_DIR);
		String         configXML      = settingMgr.get(SettingManager.SETINGKEY_CLUSTER).equals("true")
											? WikiRepository.REPOSITORY_CUSTER_FILENAME
											: WikiRepository.REPOSITORY_LOCAL_FILENAME;
		File           file           = new File(path + "/" + settingMgr.getSelectedParty() + "/" + configXML);
		
		if(file.exists() != true) {
			InputStream       inputStream   = getClass().getResourceAsStream("resources/" + configXML);
			InputStreamReader streamReader  = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader    reader        = new BufferedReader(streamReader);
			StringBuffer      buf           = new StringBuffer();
			String            line;			
			
			while((line = reader.readLine()) != null) {
				buf.append(line + "\n");
			}
			reader.close();
			file.createNewFile();

			BufferedWriter writer         = FileIO.bufferedWriter(file);
			
			writer.write(buf.toString());
			writer.flush();
			writer.close();
		}
	}

	/**
	 * Create CSS Files.
	 * @throws Exception
	 */
	private void createCssFiles() throws Exception {
		SettingManager settingMgr         = SettingManager.getInstance();

		String templateHtmlHeaderPath = settingMgr.getAbsolutePath(WikiEngine.TEMPLATE_HTMLHEADER_FILE);
	
		if (new File(templateHtmlHeaderPath).exists() != true) {
			InputStream in       = getClass().getResourceAsStream("resources/" + WikiEngine.TEMPLATE_HTMLHEADER_FILE);
			Path        destPath = Paths.get(templateHtmlHeaderPath);
			Files.copy(in, destPath);
		}
	}
	
	/**
	 * Session closer.
	 */
	public void closeSession() {
		wikiEngine_.closeSession();
	}
}
