package hsr.dsa.view;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import hsr.dsa.controller.ChatController;
import hsr.dsa.controller.ControllerManager;
import hsr.dsa.data.models.LocalUser;
import hsr.dsa.view.utils.Toast;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;

@SuppressWarnings("restriction")
public class LoginController implements FXController {
	private final ChatController profileController;
	
	private FXWindowManager windowManager;
	private String profile;

	@FXML
	private Label username;
	@FXML
	private PasswordField password;

	public LoginController() throws IOException {
		this.profileController = ControllerManager.getChatController();
	}
	
	@FXML
	public void initialize() throws IOException {
		if(this.profile != null) {
			this.username.setText(this.profile);
		}
	}
	
	@Override
	public void setWindowManager(FXWindowManager windowManager) {
		this.windowManager = windowManager;
	}

	public void login() {
		this.password.setDisable(true);
		(new Thread() {
			@Override
			public void run() {
				try {
					Map<String, Object> parameter = new HashMap<String, Object>();
					LocalUser user = profileController.getLoginProfile(profile, password.getText().trim());
					profileController.login(user, password.getText().trim());
					parameter.put("User", user);
					Platform.runLater(() -> {
						password.setDisable(false);
						windowManager.switchScene("/fxml/chatWindow/chatWindow.fxml", parameter);
					});
				} catch (IllegalStateException e) {
					Platform.runLater(() -> {
						password.setDisable(false);
						Toast.makeText(windowManager.getStage(), "Wrong Password", 2500, 100, 100);
					});
				}
			}
		}).start();
	}

	public void cancle() {
		this.windowManager.switchScene("/fxml/start.fxml");
	}

	@Override
	public void setParamater(Map<String, Object> paramater) {
		this.profile = (String) paramater.get("User");
		if(this.username != null) {
			this.username.setText(this.profile);
		}
	}
}
