package com.ht.svg.action;

import javafx.scene.control.Label;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.events.Event;

import com.ht.data.script.ScriptUtil;
import com.ht.ui.MainApplication;
import com.ht.util.UserSession;
import com.ht.web.mongo.domain.User;

/**
 * the abstract class of the run application action
 * 
 * @author ITRIS, Jordi SUC
 */
public class RunScript extends AbstractActionListener {
	
	private static final Logger log = LoggerFactory.getLogger(RunScript.class);

	/**
	 * the string names
	 */
	protected static final String commandAttributeName = "command",
			workingDirectoryAttributeName = "workingDirectory";
	private CompiledScript compiledScript = null;

	/**
	 * the constructor of the class
	 * 
	 * @param actionElement
	 *            the dom element defining the action
	 */
	public RunScript(Element actionElement) {

		super(actionElement);

		String script = actionElement.getTextContent();
		if (script == null || script.isEmpty()) {
			script = actionElement.getAttribute("script");
		}
		if (ScriptUtil.INSTANCE.getEngine() instanceof Compilable) {
			if (script != null && !script.isEmpty()) {

				Compilable compilable = (Compilable) ScriptUtil.INSTANCE
						.getEngine();
				try {
					compiledScript = compilable.compile(script);
				} catch (ScriptException ex) {
					log.error("编译RunScript动作脚本失败");
					ex.printStackTrace();
				}
			}
		}
	}

	@Override
	public void performAction(Event event) {

		if (compiledScript == null) {
			return;
		}
		isEntitled(new Runnable() {

			@Override
			public void run() {
				User user = UserSession.INSTANCE
						.getUser();
				if (user != null && user.getGroup().getYk()) {
					exeuteScript();
				} else {

					Label label = new Label("您所在的用户组没有权限执行该操作!");
					label.setId("modal_message");
					MainApplication.getMainApp().showModalMessage(label);
				}

			}
		});
	}

	private void exeuteScript() {
		if (compiledScript != null) {

			try {
				compiledScript.eval();
			} catch (ScriptException ex) {
				ex.printStackTrace();
			}
		}
	}
}
