package mi.hdm.recipes; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; public class RecipeSearch { //private final List<Recipe> recipesToSearch; //not needed when methods are static private static final Logger log = LogManager.getLogger(RecipeSearch.class); //public RecipeSearch (List<Recipe> recipesToSearch) { this.recipesToSearch = recipesToSearch; } //not needed when methods are static /** * A method to search a list of recipes for keywords. * The method searches the recipe names and the ingredients for the keywords. * * @param query a String with keywords to search for * @return a list of Recipes which contain one or several of the keywords in its name or its ingredients */ public static List<Recipe> searchByQuery(List<Recipe> recipesToSearch, String query) { if (query == null) return recipesToSearch; query = query.replaceAll("[.,!+?;-]", " ").trim(); if (query.isBlank()) return recipesToSearch; log.debug("Searching for {}", query); List<Recipe> result = new ArrayList<>(); String[] split = query.split(" "); //split String into separate words and put them into a String Array for (final Recipe r : recipesToSearch) { //search all recipes from recipesToSearch for (final String s : split) { String l = s.toLowerCase(); //convert current string of the query to lowercase! if (r.getName().toLowerCase().contains(l)) { //check if recipe name contains words from query (convert name of recipe to lowercase too) result.add(r); } for (final RecipeComponent c : r.getIngredients().keySet()) { if (c.getName().toLowerCase().contains(l)) { //check if ingredients contain words from query result.add(r); } } } } return result; } /** A method to search a list of recipes for categories. * The method filters recipes which belong to all requested categories. * * @param categoriesToSearch a list of categories to which the recipes shall belong * @return a list of recipes which belong to all categories of categoriesToSearch */ public static List<Recipe> searchByCategory(List<Recipe> recipesToSearch, List<Category> categoriesToSearch) { if (categoriesToSearch == null || categoriesToSearch.isEmpty()) return recipesToSearch; List<Recipe> result = new ArrayList<>(recipesToSearch); //create List containing all the recipes to search for (final Recipe r : recipesToSearch) { for (final Category c : categoriesToSearch) { if (!r.getCategories().contains(c)) { //if a recipe does not contain one of the categories it will be removed from the result set result.remove(r); } } } return result; } }