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

import fr.insa.clavardator.client.ui.UserSelectedEvent;
import fr.insa.clavardator.client.users.PeerUser;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.control.ListCell;

import java.io.IOException;

public class UserListItemCell extends ListCell<PeerUser> {

	private UserSelectedEvent listener;
	private UserListItemController userListItemController;
	private Node view;

	public UserListItemCell() {
		setStyle("-fx-padding: 0px");
		FXMLLoader cellLoader = new FXMLLoader(getClass().getResource("userListItem.fxml"));
		try {
			view = cellLoader.load();
			userListItemController = cellLoader.getController();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void setOnUserSelectedListener(UserSelectedEvent listener) {
		this.listener = listener;
	}

	@Override
	protected void updateItem(PeerUser item, boolean empty) {
		super.updateItem(item, empty);
		if (item == null || empty) {
			setGraphic(null);
		} else {
			setGraphic(view);
			userListItemController.setUser(item);
			userListItemController.setOnPressListener(() -> {
				if (listener != null) {
					listener.onSelected(item);
				}
			});
			userListItemController.setSelected(isSelected());
		}
	}
}
