/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ht.ui;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URL;

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.TimelineBuilder;
import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.DepthTest;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import netscape.javascript.JSObject;

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

import com.ht.data.script.ScriptUtil;
import com.ht.ui.chart.AdvCmpChart;
import com.ht.ui.controls.MessageInfoLabel;
import com.ht.ui.controls.calendar.FXCalendar;
import com.ht.ui.svg.SVGViewerManager;
import javax.script.ScriptException;

/**
 * 
 * @author Administrator
 */
public class MainApplication extends Application {

	private static final Logger log = LoggerFactory
			.getLogger(MainApplication.class);

	private static MainApplication mainApp;
	private static boolean isApplet = false;
	private Stage stage;
	private Scene scene;
	// private BorderPane root;

	private StackPane root;
	private StackPane modalDimmer;
	// private CenterRegion center;

	private MessageInfoLabel message = new MessageInfoLabel(2, 2, .8);

	private JSObject browser;

	private StringProperty host = new SimpleStringProperty("localhost");

	private Timeline modalDimmerTimeLine;
	private Timeline modalDimmerTimeLine2;

	private static CookieManager cookieManager;

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String[] args) {
		launch(args);
		System.exit(0);
	}

	public static MainApplication getMainApp() {
		return mainApp;
	}

	public static boolean isApplet() {
		return isApplet;
	}

	public static CookieManager getCookieManager() {
		return cookieManager;
	}

	@Override
	public void start(Stage primaryStage) {

		cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
		CookieHandler.setDefault(cookieManager);

		mainApp = this;
		this.stage = primaryStage;

		configureScene();
		configureStage();// 设置应用程序窗口

		createModalDimmer();// 创建蒙版区域(用于显示对话框和提示信息)

		StackPane.setAlignment(message, Pos.CENTER);
		root.getChildren().add(message);

		try {
			ScriptUtil.INSTANCE.getEngine().eval("function test() { Packages.com.ht.ui.MainApplication.test(); }");
			ScriptUtil.INSTANCE.getEngine().eval("test()");
		} catch (ScriptException ex) {
			ex.printStackTrace();
		}

	}

	public static void test() {
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				mainApp.showMessage("sdafsadfsdasd");	
			}
		});
	}


	@Override
	public void stop() throws Exception {
	}

	private void configureScene() {
		// check if applet
		try {
			browser = getHostServices().getWebContext();
			log.debug("hostservice document base : {}", getHostServices()
					.getDocumentBase());
			String codeBase = getHostServices().getCodeBase();
			if (codeBase == null || codeBase.trim().isEmpty()
					|| codeBase.startsWith("file")) {
				host.setValue("127.0.0.1");
			} else {
				host.setValue(new URL(codeBase).getHost());
			}
			isApplet = browser != null;
		} catch (Exception e) {
			isApplet = false;
			e.printStackTrace();
		}

		root = new StackPane();
		root.setAlignment(Pos.TOP_CENTER);
		if (!isApplet) {
			stage.initStyle(StageStyle.UNDECORATED);
			root.getStyleClass().add("application");
		} else {
			root.getStyleClass().add("applet");
		}
		root.setId("root");
		//root.setCache(true);

		StackPane layerPane = new StackPane();
		layerPane.setDepthTest(DepthTest.DISABLE);
		layerPane.getChildren().add(root);
		// create scene
		boolean is3dSupported = Platform
				.isSupported(ConditionalFeature.SCENE3D);
		scene = new Scene(layerPane, 1020, 700, is3dSupported);
		// if (is3dSupported) {
		// // RT-13234
		// scene.setCamera(new PerspectiveCamera());
		// }

		loadStyleSheet(scene);
	}

	private void loadStyleSheet(Scene scene) {
		scene.getStylesheets().addAll(
				MainApplication.class.getResource("main.css").toExternalForm(),
				MainApplication.class.getResource("common.css")
						.toExternalForm(),
				MainApplication.class.getResource(
						"/com/ht/ui/controls/cell/cells.css").toExternalForm(),
				AdvCmpChart.class.getResource("custom-chart.css")
						.toExternalForm(),
				// Workaround for CSS issue with HTML Editor
				// com.sun.javafx.scene.web.skin.HTMLEditorSkin.class.getResource("html-editor.css").toExternalForm(),
				// 日历控件CSS
				FXCalendar.class.getResource(
						"/com/ht/ui/controls/calendar/calendar_styles.css")
						.toExternalForm());
	}

	private void createModalDimmer() {
		// create modal dimmer, to dim screen when showing modal dialogs
		modalDimmer = new StackPane();
		modalDimmer.setId("ModalDimmer");
		modalDimmer.setAlignment(Pos.CENTER);
		modalDimmer.setVisible(false);

		modalDimmerTimeLine = TimelineBuilder
				.create()
				.keyFrames(
						new KeyFrame(Duration.seconds(.3),
								new EventHandler<ActionEvent>() {

									@Override
									public void handle(ActionEvent t) {
										modalDimmer.setCache(false);
									}
								}, new KeyValue(modalDimmer.opacityProperty(),
										1, Interpolator.EASE_BOTH))).build();

		modalDimmerTimeLine2 = TimelineBuilder
				.create()
				.keyFrames(
						new KeyFrame(Duration.seconds(.3),
								new EventHandler<ActionEvent>() {

									public void handle(ActionEvent t) {
										modalDimmer.setCache(false);
										modalDimmer.setVisible(false);
										modalDimmer.getChildren().clear();
										
									}
								}, new KeyValue(modalDimmer.opacityProperty(),
										0, Interpolator.EASE_BOTH))).build();

		root.getChildren().add(modalDimmer);
	}

	private void configureStage() {
		stage.setTitle("PDM能源监控管理系统");
		stage.setX(0);
		stage.setY(0);
		stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth());
		stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight());
		stage.setScene(this.scene);
		stage.show();
	}

	public void showMessage(String value) {
		message.show(value);
	}

	/**
	 * Show the given node as a floating dialog over the whole application, with
	 * the rest of the application dimmed out and blocked from mouse events.
	 * 
	 * @param node
	 */
	public void showModalMessage(final Node node) {
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
		for (Node n : modalDimmer.getChildren()) {
			n.setVisible(false);
		}
		//modalDimmer.getChildren().clear();
		
		if (modalDimmer.getChildren().contains(node)) {
			node.setVisible(true);
		} else {
			modalDimmer.getChildren().add(node);
			StackPane.setAlignment(node, Pos.CENTER);
		}
		modalDimmer.setOpacity(0);
		modalDimmer.setVisible(true);
		modalDimmer.setCache(true);
		modalDimmerTimeLine.play();
			}
		});

	}

	/**
	 * Hide any modal message that is shown
	 */
	public void hideModalMessage() {
		
		if (modalDimmer.getChildren().size() > 1) { 
			modalDimmer.getChildren().remove(modalDimmer.getChildren().size() - 1);
			modalDimmer.getChildren().get(modalDimmer.getChildren().size() - 1).setVisible(true);
			modalDimmer.setCache(true);
		} else {
			modalDimmer.setCache(true);
			modalDimmerTimeLine2.play();
		}
	}

	public void hideModalMessageFast() {

		if (modalDimmer.getChildren().size() > 1) { 
			modalDimmer.getChildren().remove(modalDimmer.getChildren().size() - 1);
			modalDimmer.getChildren().get(modalDimmer.getChildren().size() - 1).setVisible(true);
			modalDimmer.setCache(true);
		} else {
			modalDimmer.setCache(false);
			modalDimmer.setVisible(false);
			modalDimmer.getChildren().clear();
		}
	}
	
	public StringProperty hostProperty() {
		return host;
	}

	public String getHost() {
		return host.get();
	}

	public SVGViewerManager getSvgViewer() {
		return null;
	}
	public void showDefaultView() {
	}

}
