using MongoDB.Bson; using MongoDB.Driver; using SushiBarContracts.BindingModels; using SushiBarContracts.SearchModels; using SushiBarContracts.StoragesContracts; using SushiBarContracts.ViewModels; using SushiBarMongoDB.Models; using System.Xml; using Task = SushiBarMongoDB.Models.Task; namespace SushiBarMongoDB.Implements { public class TaskStorage : ITaskStorage { public void ClearEntity() { using var context = new SushiBarMongoDB(); context.GetCollection("Tasks") .DeleteMany(Builders.Filter.Empty); } public List GetFullList() { using var context = new SushiBarMongoDB(); var tasks = context.GetCollection("Tasks").Find(Builders.Filter.Empty).ToList(); return tasks.Select(x => x.GetViewModel).ToList(); } public List GetFilteredList(TaskSearchModel model) { using var context = new SushiBarMongoDB(); if(!model.Id.HasValue) return new List(); var filterBuilder = Builders.Filter; var filter = filterBuilder.Empty; filter = filterBuilder.Eq("Id", model.Id); var tasks = context.GetCollection("Tasks").Find(filter).ToList(); return tasks.Select(x => x.GetViewModel).ToList(); } public TaskViewModel? GetElement(TaskSearchModel model) { using var context = new SushiBarMongoDB(); var tasks = context.GetCollection("Tasks"); if (!model.Id.HasValue) return null; return tasks.Find(x => x.Id == model.Id).FirstOrDefault()?.GetViewModel; } public TaskViewModel? Insert(TaskBindingModel model) { using var context = new SushiBarMongoDB(); var tasks = context.GetCollection("Tasks"); model.Id = (int)tasks.CountDocuments(FilterDefinition.Empty) + 1; var newTask = Task.Create(model); if (newTask == null) return null; tasks.InsertOne(newTask); return newTask.GetViewModel; } public TaskViewModel? Update(TaskBindingModel model) { using var context = new SushiBarMongoDB(); var task = context.GetCollection("Tasks").Find(x => x.Id == model.Id).FirstOrDefault(); if (task == null) return null; task.Update(model); context.GetCollection("Tasks").ReplaceOne(x => x.Id == model.Id, task); return task.GetViewModel; } public TaskViewModel? Delete(TaskBindingModel model) { using var context = new SushiBarMongoDB(); var element = context.GetCollection("Tasks").Find(x => x.Id == model.Id).FirstOrDefault(); if (element != null) { context.GetCollection("Tasks").DeleteOne(x => x.Id == model.Id); return element.GetViewModel; } return null; } } }