package com.ht.ui.user;

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.TimelineBuilder;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.util.Duration;

import com.ht.ui.MainApplication;
import com.ht.ui.util.MessageConstants;
import com.ht.util.UserSession;
import com.ht.web.hessian.HessianFactoryManger;
import com.ht.web.mongo.domain.User;
import com.ht.web.remoting.HessianResponse;

public class UserLoginDialog extends Group {

	private static UserLoginDialog instance;

	public static synchronized UserLoginDialog getInstance() {

		if (instance == null) {
			instance = new UserLoginDialog();
		}
		return instance;
	}
	
	private VBox vb = new VBox(20);

	private UserLoginDialog() {
		//super(20);

		vb.setId("UserLoginDialog");
		vb.getStyleClass().add("window");
		vb.setAlignment(Pos.TOP_CENTER);
		getChildren().add(vb);
		//vb.setMaxSize(400, 250);
		vb.setMinWidth(400);

		// block mouse clicks
		setOnMouseClicked(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent t) {
				t.consume();
//				if (message.getOpacity() >= 1) {
//					messageAnimate.play();
//				}
			}
		});

		Label title = new Label("用户登录");
		title.setId("title");
		vb.getChildren().add(title);
		
		if (!MainApplication.isApplet()) {
			HBox hb = new HBox();
			hb.setAlignment(Pos.CENTER);
			host = new TextField("localhost");
			MainApplication.getMainApp().hostProperty().bind(host.textProperty());
			hb.getChildren().addAll(new Label("http://"), host);
			vb.getChildren().add(hb);
		}

		final GridPane gridPane = new GridPane();
		gridPane.setHgap(10);
		gridPane.setVgap(10);
		gridPane.setMaxWidth(250);
		VBox.setVgrow(gridPane, Priority.ALWAYS);

		Label usernameLabel = new Label("用户名:");
		GridPane.setConstraints(usernameLabel, 0, 0);
		GridPane.setHalignment(usernameLabel, HPos.RIGHT);
		gridPane.getChildren().add(usernameLabel);

		usernameValue = new TextField();
		usernameValue.setPrefWidth(150);
		usernameValue.setPromptText("请输入用户名");
		usernameValue.requestFocus();
		GridPane.setConstraints(usernameValue, 1, 0);
		GridPane.setHalignment(usernameValue, HPos.LEFT);
		gridPane.getChildren().add(usernameValue);

		Label passwordLabel = new Label("密码:");
		GridPane.setConstraints(passwordLabel, 0, 1);
		GridPane.setHalignment(passwordLabel, HPos.RIGHT);
		gridPane.getChildren().add(passwordLabel);

		passwordValue = new PasswordField();
		passwordValue.setPromptText("请输入密码");
		passwordValue.setPrefWidth(150);
		GridPane.setConstraints(passwordValue, 1, 1);
		GridPane.setHalignment(passwordValue, HPos.LEFT);
		gridPane.getChildren().add(passwordValue);

		vb.getChildren().add(gridPane);

		HBox hb = new HBox(10);
		hb.setAlignment(Pos.CENTER);

		Button regist = new Button("注册");
		regist.setPrefWidth(80);
		regist.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				String username = usernameValue.getText().trim();
				String password = passwordValue.getText().trim();
				if (!username.isEmpty() && !password.isEmpty()) {

					try {
						HessianResponse resp = HessianFactoryManger.INSTANCE.getUserService().regist(username, password);
						postLogin(resp);
					} catch (Exception e) {
						MainApplication.getMainApp().showMessage(MessageConstants.ERROR_SERVER_ERROR);
					}

				} else {// 用户名和密码不允许为空
					MainApplication.getMainApp().showMessage("用户名或密码为空");
				}
			}
		});

		Button ok = new Button("登录");
		ok.setPrefWidth(80);
		ok.setDefaultButton(true);
		ok.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {

//				if (host != null) {
//					MainApplication.getMainApp().hostProperty().setValue(host.getText());
//				}
				
				String username = usernameValue.getText().trim();
				String password = passwordValue.getText().trim();
				if (!username.isEmpty() && !password.isEmpty()) {
					try {
						HessianResponse resp = HessianFactoryManger.INSTANCE
								.getUserService().login(username, password);
						postLogin(resp);
					} catch (Exception e) {
						MainApplication.getMainApp().showMessage("无法连接到服务器");
					}

				} else {// 用户名和密码不允许为空

					MainApplication.getMainApp().showMessage("用户名或密码不能为空");
				}

			};
		});

		Button cancel = new Button("取消");
		cancel.setPrefWidth(80);
		cancel.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {

				MainApplication.getMainApp().hideModalMessage();
				if (onCancel != null) {
					onCancel.run();
					onCancel = null;
				} 
			}
		});

		hb.getChildren().addAll(regist, ok, cancel);

		vb.getChildren().add(hb);
	}

	public void showDialog(Runnable onLogin) {
		showDialog(onLogin, null, null);
	}
	
	public void showDialog(Runnable onLogin, Runnable onCancel, String msg) {
		this.onLogin = onLogin;
		this.onCancel = onCancel;
		this.passwordValue.clear();
		this.usernameValue.clear();
		
		/*for test TODO: 删除该部分*/
		usernameValue.setText("admin");
		passwordValue.setText("admin");
		/*for test*/
		
		MainApplication.getMainApp().showModalMessage(this);
		
		if (msg != null) {
			MainApplication.getMainApp().showMessage(msg);
		}
	}

	public void showDialog(Runnable onLogin, String msg) {
		showDialog(null);
		MainApplication.getMainApp().showMessage(msg);
	}

	private void postLogin(HessianResponse resp) {
		if (resp == null) {
			MainApplication.getMainApp().showMessage("服务器响应超时.");
			return;
		}
		if (resp.isSuccessful() && resp.isLogin()) {
			if (host != null) {
				host.setDisable(true);
			}

			UserSession.INSTANCE.setUser(
					(User) resp.getData());
			MainApplication.getMainApp().hideModalMessageFast();
			if (onLogin != null) {
				onLogin.run();
				onLogin = null;
			}
		} else {

			MainApplication.getMainApp().showMessage(resp.getMsg());
		}
	}

	private Runnable onLogin;
	private Runnable onCancel;
	private PasswordField passwordValue;
	private TextField usernameValue;
	private TextField host;
}
