package fr.insa.clavardator.client.ui;

import fr.insa.clavardator.client.users.CurrentUser;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

import java.beans.PropertyChangeEvent;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * Controller for the main screen toolbar
 */
public class ToolbarController implements Initializable {

	@FXML
	private Label currentUsernameLabel;

	private ButtonPressEvent editListeners;
	private ButtonPressEvent aboutListeners;

	public void setEditListener(ButtonPressEvent listener) {
		editListeners = listener;
	}

	public void setAboutListener(ButtonPressEvent listener) {
		aboutListeners = listener;
	}

	public void onEditPress() {
		if (editListeners != null) {
			editListeners.onPress();
		}
	}

	public void onAboutPress() {
		if (aboutListeners != null) {
			aboutListeners.onPress();
		}
	}

	/**
	 * Update the text on current username change
	 *
	 * @param propertyChangeEvent The change event
	 */
	private void onUsernameChange(PropertyChangeEvent propertyChangeEvent) {
		if (propertyChangeEvent.getPropertyName().equals("username")) {
			final String newUsername = (String) propertyChangeEvent.getNewValue();
			currentUsernameLabel.setText(newUsername);
		}
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		CurrentUser.getInstance().addObserver(this::onUsernameChange);
	}
}
