Newer
Older
package no.ntnu.idatt1002.demo.controller;
import javafx.animation.FadeTransition;
HSoreide
committed
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.event.ActionEvent;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.util.Duration;
import no.ntnu.idatt1002.demo.data.recipes.FileHandler;
import no.ntnu.idatt1002.demo.data.recipes.FoodItem;
import no.ntnu.idatt1002.demo.data.recipes.IngredientsAtHand;
public class AddIngredientController implements Initializable {
private ObservableList<String> ingredients;
private String[] ingredientsList;
@FXML
private Button addBtn;
@FXML
private ListView<String> listView;
@FXML
private TextField searchBar;
@FXML
private Button searchBtn;
@FXML
private Label status;
private String statusText = "Added: ";
void addToFridge(ActionEvent event) throws IOException {
IngredientsAtHand ingredientsAtHand = FileHandler.readIngredientsAtHand("Fridge");
FoodItem item = FoodItem.valueOf(listView.getSelectionModel().getSelectedItem().replace(" ", "_").toUpperCase());
assert ingredientsAtHand != null;
if(!ingredientsAtHand.atHand(item)) {
ingredientsAtHand.addIngredient(item);
FileHandler.writeIngredientsAtHand(ingredientsAtHand, "Fridge");
if(status.isVisible() && status.getText().isBlank()) {
statusText += String.format("%s", item.label);
} else if (status.isVisible()){
statusText += String.format(", %s", item.label);
}
status.setText(statusText); // Only if not already in list!!
}
}
@FXML
listView.getItems().clear();
listView.getItems().addAll(searchList(searchBar.getText(),
Arrays.stream(FoodItem.values()).toList().stream().map(value -> value.label).toArray(String[]::new))); // String[]
HSoreide
committed
private List<String> searchList(String searchWords, String[] listOfStrings) {
String[] searchWordsArray = searchWords.trim().split(" ");
return Arrays.stream(listOfStrings).filter((in) -> {
return Arrays.stream(searchWordsArray).allMatch((word) ->
in.toLowerCase().contains(word.toLowerCase()));
}).collect(Collectors.toList());
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
listView.setItems(FXCollections.observableArrayList(Arrays.stream(FoodItem.values()).map(value -> value.label).toList()));
HSoreide
committed
Platform.runLater(() -> searchBar.requestFocus());
status.setWrapText(true);