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

import com.jfoenix.controls.JFXButton;
import fr.insa.clavardator.client.ui.ButtonPressEvent;
import fr.insa.clavardator.client.ui.UserSelectedEvent;
import fr.insa.clavardator.client.users.PeerUser;
import fr.insa.clavardator.client.users.UserList;
import fr.insa.clavardator.lib.users.User;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;

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

public class UserListController implements Initializable {
	@FXML
	private ListView<PeerUser> peerUserListView;
	@FXML
	private JFXButton refreshButton;

	private ButtonPressEvent refreshUserListener;
	private UserSelectedEvent userSelectedListener;

	public UserListController() {
	}

	public void setRefreshUserListener(ButtonPressEvent listener) {
		refreshUserListener = listener;
	}

	public void setUserSelectedListener(UserSelectedEvent listener) {
		userSelectedListener = listener;
	}

	public void onRefreshUserListPress() {
		if (refreshUserListener != null) {
			refreshUserListener.onPress();
		}
	}

	/**
	 * Enables or disables the refresh button
	 *
	 * @param enabled True to enable, false otherwise
	 */
	public void setRefreshButtonEnabled(boolean enabled) {
		refreshButton.setDisable(!enabled);
	}

	private void onUserSelected(@org.jetbrains.annotations.NotNull PeerUser user) {
		final User currentSelectedUser = peerUserListView.getSelectionModel().getSelectedItem();
		if (!user.equals(currentSelectedUser)) {
			peerUserListView.getSelectionModel().select(user);
			userSelectedListener.onSelected(user);
		}
	}

	@Override
	public void initialize(URL url, ResourceBundle rb) {
		peerUserListView.setCellFactory(listView -> {
			final UserListItemCell cell = new UserListItemCell();
			cell.setOnUserSelectedListener(this::onUserSelected);
			return cell;
		});
	}

	/**
	 * Sets the user list to subscribe to
	 *
	 * @param userList The user list to use
	 */
	public void setUserList(UserList userList) {
		peerUserListView.setItems(userList.getUserObservableList());
	}
}