using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoftwareInstallationFileImplement { public class PackageStorage : IPackageStorage { private readonly DataFileSingleton source; public PackageStorage() { source = DataFileSingleton.GetInstance(); } public PackageViewModel? Delete(PackageBindingModel model) { var element = source.Packages.FirstOrDefault(x => x.Id == model.Id); if (element != null) { source.Packages.Remove(element); source.SavePackages(); return element.GetViewModel; } return null; } public PackageViewModel? GetElement(PackageSearchModel model) { if (string.IsNullOrEmpty(model.PackageName) && !model.Id.HasValue) { return null; } return source.Packages.FirstOrDefault(x => (!string.IsNullOrEmpty(model.PackageName) && x.PackageName == model.PackageName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(PackageSearchModel model) { if (string.IsNullOrEmpty(model.PackageName)) { return new(); } return source.Packages.Where(x => x.PackageName.Contains(model.PackageName)).Select(x => x.GetViewModel).ToList(); } public List GetFullList() { return source.Packages.Select(x => x.GetViewModel).ToList(); } public PackageViewModel? Insert(PackageBindingModel model) { model.Id = source.Packages.Count > 0 ? source.Packages.Max(x => x.Id) + 1 : 1; var newPackage = Package.Create(model); if (newPackage == null) { return null; } source.Packages.Add(newPackage); source.SavePackages(); return newPackage.GetViewModel; } public PackageViewModel? Update(PackageBindingModel model) { var package = source.Packages.FirstOrDefault(x => x.Id == model.Id); if (package == null) { return null; } package.Update(model); source.SavePackages(); return package.GetViewModel; } } }