using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using Model; namespace ConsoleApp.Menu { /// /// An utility to find a recipe. /// public class SearcherRecipe : SelectMenu { #region Attribute private RecipeCollection _recipeOnSearch; #endregion #region Properties /// /// A collection of recipe where the title contain the search string /// public RecipeCollection SearchResult { get; private set; } /// /// The search string /// public string ResearchStr { get; set; } #endregion /// /// Constructor of the SearcherRecipe utility. /// /// The collection of recipe where to search public SearcherRecipe(RecipeCollection recipeOnSearch) { _recipeOnSearch = recipeOnSearch; SearchResult = _recipeOnSearch; ResearchStr = ""; } #region Methodes /// /// Launch a search by name request in the collection of Recipe with with a string. /// /// The string for search /// True if the result of the search gave at least 1 element. False otherwise. public bool ComputeSearch(string researchStr = "") { ResearchStr = researchStr; SearchResult = _recipeOnSearch.ResearchByName(ResearchStr.ToLower()); _maxLines = SearchResult.Count - 1; return SearchResult.Count > 0; } public override void UpdateDisplay() { StringBuilder sb = new StringBuilder(); sb.AppendLine("---------------------------------------------------------"); sb.AppendLine($" Research: {ResearchStr}"); sb.AppendLine("---------------------------------------------------------"); for (int i = 0; i < SearchResult.Count; i++) { if (i == CurrentLine) { CurrentSelected = SearchResult[i]; sb.Append($">"); } sb.AppendLine($" [ {SearchResult[i].Id} ]:\t{SearchResult[i].Title} "); } Console.Clear(); Console.WriteLine(sb); } /// /// Launch and pilot the search menu. /// /// The collection of recipe where to search /// The recipe selected public static Recipe? ResearchOn(RecipeCollection recipeOnSearch) { SearcherRecipe sr = new SearcherRecipe(recipeOnSearch); StringBuilder sb = new StringBuilder(); sr.ComputeSearch(); sr.UpdateDisplay(); ConsoleKeyInfo cki; do { cki = Console.ReadKey(true); switch (cki.Key) { case ConsoleKey.UpArrow: sr.SelectPrevioustLine(); break; case ConsoleKey.DownArrow: sr.SelectNextLine(); break; case ConsoleKey.Backspace: if (sb.Length > 0) { sb.Remove(sb.Length - 1, 1); sr.ComputeSearch(sb.ToString()); } break; default: sb.Append(cki.KeyChar); sr.ComputeSearch(sb.ToString()); break; } sr.UpdateDisplay(); } while (cki.Key != ConsoleKey.Enter); return sr.CurrentSelected; } #endregion } }