using Models; using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.Serialization; namespace LocalEndpoint { internal class RecipesDatabase { private static readonly DataContractSerializer RECIPES_SERIALIZER = new DataContractSerializer(typeof(List)); private readonly Dictionary recipes = new Dictionary(); private readonly string dbPath; public RecipesDatabase(string path) { dbPath = path; if (!File.Exists(dbPath)) { File.Create(dbPath); } if (new FileInfo(dbPath).Length == 0) return; //file is empty thus there is nothing to deserialize Console.WriteLine(File.ReadAllText(dbPath)); using (var stream = File.OpenRead(dbPath)) { var recipes = RECIPES_SERIALIZER.ReadObject(stream) as List; recipes.ForEach(recipe => this.recipes.Add(recipe.Info.Id, recipe)); } } private void SaveAll() { using (var stream = File.OpenWrite(dbPath)) { RECIPES_SERIALIZER.WriteObject(stream, recipes.Values.ToList()); } } public Recipe? Lookup(Guid id) { Recipe? recipe; recipes.TryGetValue(id, out recipe); return recipe; } public Recipe Get(Guid id) { return recipes[id]; } public void Insert(Recipe recipe) { recipes[recipe.Info.Id] = recipe; SaveAll(); } public void Remove(Guid id) { recipes.Remove(id); SaveAll(); } public ImmutableList ListAll() { return recipes.Values.ToImmutableList(); } } }