using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContracts;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationFileImplement.Models;

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<PackageViewModel> GetFilteredList(PackageSearchModel model)
        {
            if (string.IsNullOrEmpty(model.PackageName))
            {
                return new();
            }
            return _source.Packages
                .Select(x => x.GetViewModel)
                .Where(x => x.PackageName.Contains(model.PackageName))
                .ToList();
        }

        public List<PackageViewModel> 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;
        }
    }
}
