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

import fr.insa.clavardator.client.users.PeerUser;
import fr.insa.clavardator.lib.users.UserState;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.shape.Circle;

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

/**
 * Controller for the user indicator, showing the connection status
 */
public class UserActiveIndicatorController implements Initializable {

	@FXML
	private Circle circle;
	private PeerUser user;

	/**
	 * Sets the new circle color
	 *
	 * @param isActive True for active color, false for inactive
	 */
	private void updateState(boolean isActive) {
		circle.getStyleClass().clear();
		if (isActive) {
			circle.getStyleClass().add("active-user-dot");
		} else {
			circle.getStyleClass().add("inactive-user-dot");
		}
	}

	/**
	 * Update the indicator color on user state change.
	 * The indicator becomes active only if the user state goes to connected.
	 *
	 * @param propertyChangeEvent The change event
	 */
	private void onStateChange(PropertyChangeEvent propertyChangeEvent) {
		if (propertyChangeEvent.getPropertyName().equals("state")) {
			final UserState newState = (UserState) propertyChangeEvent.getNewValue();
			Platform.runLater(() -> updateState(newState == UserState.CONNECTED));
		}
	}

	/**
	 * Sets the user associated to this indicator
	 *
	 * @param user The user to set
	 */
	public void setUser(PeerUser user) {
		if (this.user != null) {
			// remove old observer before setting new user
			this.user.removeObserver(this::onStateChange);
		}
		this.user = user;
		user.addObserver(this::onStateChange);
		updateState(user.isActive());
	}

	/**
	 * Sets the indicator's radius
	 *
	 * @param value The radius in pixels
	 */
	public void setSize(double value) {
		circle.setRadius(value);
	}

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

}
