using PlumbingRepairContracts.BindingModels; using PlumbingRepairContracts.SearchModels; using PlumbingRepairContracts.StoragesContracts; using PlumbingRepairContracts.ViewModels; using PlumbingRepairDataModels.Models; using PlumbingRepairFileImplement.Models; namespace PlumbingRepairFileImplement.Implements { public class StoreStorage : IStoreStorage { private readonly DataFileSingleton source; public StoreStorage() { source = DataFileSingleton.GetInstance(); } public StoreViewModel? GetElement(StoreSearchModel model) { if (string.IsNullOrEmpty(model.StoreName) && !model.Id.HasValue) { return null; } return source.Stores.FirstOrDefault(x => (!string.IsNullOrEmpty(model.StoreName) && x.StoreName == model.StoreName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(StoreSearchModel model) { if (string.IsNullOrEmpty(model.StoreName)) { return new(); } return source.Stores.Where(x => x.StoreName.Contains(model.StoreName)).Select(x => x.GetViewModel).ToList(); } public List GetFullList() { return source.Stores.Select(x => x.GetViewModel).ToList(); } public StoreViewModel? Insert(StoreBindingModel model) { model.Id = source.Stores.Count > 0 ? source.Stores.Max(x => x.Id) + 1 : 1; var newStore = Store.Create(model); if (newStore == null) { return null; } source.Stores.Add(newStore); source.SaveStores(); return newStore.GetViewModel; } public StoreViewModel? Update(StoreBindingModel model) { var store = source.Stores.FirstOrDefault(x => x.Id == model.Id); if (store == null) { return null; } store.Update(model); source.SaveStores(); return store.GetViewModel; } public StoreViewModel? Delete(StoreBindingModel model) { var element = source.Stores.FirstOrDefault(x => x.Id == model.Id); if (element != null) { source.Stores.Remove(element); source.SaveStores(); return element.GetViewModel; } return null; } public bool SellWork(IWorkModel model, int quantity) { if (source.Stores.Select(x => x.StoreWorks.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum() < quantity) { return false; } foreach (var store in source.Stores.Where(x => x.StoreWorks.ContainsKey(model.Id))) { int QuantityInCurrentShop = store.StoreWorks[model.Id].Item2; if (QuantityInCurrentShop <= quantity) { store.StoreWorks.Remove(model.Id); quantity -= QuantityInCurrentShop; } else { store.StoreWorks[model.Id] = (store.StoreWorks[model.Id].Item1, QuantityInCurrentShop - quantity); quantity = 0; } if (quantity == 0) { return true; } } return false; } } }