diff --git a/src/main/java/com/mousetech/gourmetj/utils/YamlShoppingList.java b/src/main/java/com/mousetech/gourmetj/utils/YamlShoppingList.java new file mode 100644 index 0000000..61c23e9 --- /dev/null +++ b/src/main/java/com/mousetech/gourmetj/utils/YamlShoppingList.java @@ -0,0 +1,71 @@ +package com.mousetech.gourmetj.utils; + +import java.io.ByteArrayOutputStream; +import java.io.PrintWriter; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.primefaces.model.ByteArrayContent; +import org.primefaces.model.StreamedContent; + +import com.mousetech.gourmetj.ShopIngredient; + +/** + * Construct a Primefaces file output content for an ingredient + * list in YAML format. + * + * @author timh + * @since Jan 15, 2022 + */ + +public class YamlShoppingList { + + public static StreamedContent createDownload( + List ingredientList) { + ByteArrayOutputStream ary = new ByteArrayOutputStream(); + PrintWriter wtr = new PrintWriter(ary); + wtr.println("---"); + formatContent(wtr, ingredientList); + wtr.close(); + byte[] bas = ary.toByteArray(); + + StreamedContent dlList = new ByteArrayContent(bas, + "text/text", "shopping_list.yml"); + return dlList; + } + + /** + * Output line items in the ingredient list with topics for + * each Shopping Category. + * + * @param wtr Output Writer + * @param ingredientList Ingredient list to output. + */ + private static void formatContent(PrintWriter wtr, + List ingredientList) { + String oldShopcat = null; + for (ShopIngredient ing : ingredientList) { + String newShopcat = ing.getShopCat(); + if (StringUtils.isBlank(newShopcat)) { + newShopcat = "Unassigned"; + } + if (!StringUtils.equals(newShopcat, oldShopcat)) { + wtr.println(newShopcat + ":"); + oldShopcat = newShopcat; + } + wtr.print(" - "); + String displa = ing.getDisplayAmount(); + wtr.print(displa); + if (!displa.isBlank()) { + wtr.print(' '); + } + String unit = ing.getUnit(); + if (StringUtils.isNotBlank(unit)) { + wtr.print(unit); + wtr.print(' '); + } + wtr.println(ing.getItem()); + } + } + +}