package fr.insa.clavardator.client.ui.chat;

import fr.insa.clavardator.client.ui.users.UserActiveIndicatorController;
import fr.insa.clavardator.client.users.PeerUser;
import javafx.application.Platform;
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 chat title
 */
public class ChatHeaderController implements Initializable {

	@FXML
	private Label remoteUsernameLabel;
	@FXML
	private UserActiveIndicatorController indicatorController;
	private PeerUser user;

	/**
	 * Updates username on remote user change
	 *
	 * @param propertyChangeEvent THe change event
	 */
	private void onUsernameChange(PropertyChangeEvent propertyChangeEvent) {
		if (propertyChangeEvent.getPropertyName().equals("username")) {
			final String newUsername = (String) propertyChangeEvent.getNewValue();
			Platform.runLater(() -> remoteUsernameLabel.setText(newUsername));
		}
	}

	/**
	 * Sets the remote user we are currently chatting to
	 *
	 * @param remoteUser The remote user to set
	 */
	public void setRemoteUser(PeerUser remoteUser) {
		if (this.user != null) {
			// remove old observer before setting new user
			this.user.removeObserver(this::onUsernameChange);
		}
		this.user = remoteUser;
		user.addObserver(this::onUsernameChange);
		remoteUsernameLabel.setText(remoteUser.getUsername());
		indicatorController.setUser(remoteUser);
		indicatorController.setSize(10.0);
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {
	}
}
