You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.9 KiB
76 lines
1.9 KiB
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<Recipe>));
|
|
|
|
private readonly Dictionary<Guid, Recipe> recipes = new Dictionary<Guid, Recipe>();
|
|
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<Recipe>;
|
|
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<Recipe> ListAll()
|
|
{
|
|
return recipes.Values.ToImmutableList();
|
|
}
|
|
|
|
}
|
|
}
|