package com.ht.svg.action;

import javafx.application.Platform;
import javafx.event.EventHandler;

import com.ht.ui.MainApplication;
import com.ht.ui.controls.window.MessageDialog;
import com.ht.ui.util.HessianResponseTask;
import com.ht.ui.util.MessageConstants;
import com.ht.ui.util.UserSecurityUtil;
import com.ht.util.UserSession;
import com.ht.util.WorkQueue;
import com.ht.web.hessian.HessianFactoryManger;
import com.ht.web.mongo.domain.User;
import com.ht.web.remoting.HessianResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ActionUtil {

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

	public static void ykFromScript(final String varName, final boolean state) {
		log.info("执行遥控命令");

		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				MessageDialog.buildConfirmation("提示", "您确定要执行该遥控操作吗？",
						new EventHandler<javafx.event.Event>() {
							@Override
							public void handle(javafx.event.Event event) {

								UserSecurityUtil
										.verifyUserAuthority(new Runnable() {
											public void run() {
												User user = UserSession.INSTANCE
														.getUser();
												if (user != null
														&& user.getGroup()
																.getYk()) {

													ActionUtil.yk(varName, state);

												} else {

													MainApplication
															.getMainApp()
															.showMessage(
																	"您所在的用户组没有权限执行该操作!");
												}

											}
										});

							}
						}, null);

			}
		});
	}

	public static void yk(final String varName, final boolean state) {
		HessianResponseTask task = new HessianResponseTask() {

			@Override
			protected HessianResponse call() throws Exception {
				try {
					return HessianFactoryManger.INSTANCE.getTagVarService().yk(
							varName, state);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			public void successResponse(HessianResponse resp) {
				if (resp.getMsg().isEmpty()) {
					MainApplication.getMainApp().showMessage("您的操作已执行");
				} else {
					MainApplication.getMainApp()
							.showMessage(resp.getMsg());
				}
			}

			@Override
			public void nullResponse() {
				MainApplication.getMainApp().showMessage(
						MessageConstants.ERROR_APP_ERROR);
			}

			@Override
			public void failureResponse(HessianResponse resp) {
				MainApplication.getMainApp().showMessage(resp.getMsg());
			}

		};
		WorkQueue.INSTANCE.execute(task);
	}
}
