using MongoDB.Bson; using MongoDB.Driver; using SushiBarContracts.BindingModels; using SushiBarContracts.SearchModels; using SushiBarContracts.StoragesContracts; using SushiBarContracts.ViewModels; using SushiBarMongoDB.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SushiBarMongoDB.Implements { public class BuyerStorage : IBuyerStorage { public void ClearEntity() { using var context = new SushiBarMongoDB(); context.GetCollection("Buyers") .DeleteMany(Builders.Filter.Empty); } public List GetFullList() { using var context = new SushiBarMongoDB(); var buyers = context.GetCollection("Buyers"); return buyers.Find(Builders.Filter.Empty) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(BuyerSearchModel model) { if(string.IsNullOrEmpty(model.BuyerName)) return new List(); using var context = new SushiBarMongoDB(); var buyers = context.GetCollection("Buyers"); var filterBuilder = Builders.Filter; var filter = filterBuilder.Regex(x => x.BuyerName, new BsonRegularExpression(model.BuyerName)); return buyers .Find(filter) .ToList() .Select(x => x.GetViewModel) .ToList(); } public BuyerViewModel? GetElement(BuyerSearchModel model) { if (!model.Id.HasValue) { return null; } using (var context = new SushiBarMongoDB()) { var buyers = context.GetCollection("Buyers"); var filterBuilder = Builders.Filter; var filter = filterBuilder.Empty; if (!model.Id.HasValue) { filter &= filterBuilder.Eq(x => x.Id, model.Id); } return buyers.Find(filter) .FirstOrDefault() ?.GetViewModel; } } public BuyerViewModel? Insert(BuyerBindingModel model) { using var context = new SushiBarMongoDB(); var buyers = context.GetCollection("Buyers"); model.Id = (int)buyers.CountDocuments(FilterDefinition.Empty)+1; var buyer = Buyer.Create(model); buyers.InsertOne(buyer); return buyer.GetViewModel; } public BuyerViewModel? Update(BuyerBindingModel model) { using var context = new SushiBarMongoDB(); var buyers = context.GetCollection("Buyers"); var filter = Builders.Filter.Eq(x => x.Id, model.Id); var buyer = buyers.Find(filter).FirstOrDefault(); if (buyer == null) { return null; } buyer.Update(model); buyers.ReplaceOne(filter, buyer); return buyer.GetViewModel; } public BuyerViewModel? Delete(BuyerBindingModel model) { using var context = new SushiBarMongoDB(); var categories = context.GetCollection("Buyers"); var filter = Builders.Filter.Eq(x => x.Id, model.Id); var category = categories.FindOneAndDelete(filter); return category?.GetViewModel; } } }