using System.IO.Abstractions; using AutoMapper; using Recyclarr.TrashLib.Config.Services; namespace Recyclarr.TrashLib.Config.Parsing; public class ConfigurationLoader : IConfigurationLoader { private readonly ConfigParser _parser; private readonly IMapper _mapper; private readonly ConfigValidationExecutor _validator; public ConfigurationLoader(ConfigParser parser, IMapper mapper, ConfigValidationExecutor validator) { _parser = parser; _mapper = mapper; _validator = validator; } public ICollection LoadMany( IEnumerable configFiles, SupportedServices? desiredServiceType = null) { return configFiles .SelectMany(x => Load(x, desiredServiceType)) .ToList(); } public IReadOnlyCollection Load(IFileInfo file, SupportedServices? desiredServiceType = null) { return ProcessLoadedConfigs(_parser.Load(file), desiredServiceType); } public IReadOnlyCollection Load(string yaml, SupportedServices? desiredServiceType = null) { return ProcessLoadedConfigs(_parser.Load(yaml), desiredServiceType); } public IReadOnlyCollection Load( Func streamFactory, SupportedServices? desiredServiceType = null) { return ProcessLoadedConfigs(_parser.Load(streamFactory), desiredServiceType); } private IReadOnlyCollection ProcessLoadedConfigs( RootConfigYaml? config, SupportedServices? desiredServiceType) { if (config is null) { return Array.Empty(); } if (!_validator.Validate(config)) { return Array.Empty(); } var convertedConfigs = new List(); if (desiredServiceType is null or SupportedServices.Radarr) { convertedConfigs.AddRange( ValidateAndMap(config.Radarr)); } if (desiredServiceType is null or SupportedServices.Sonarr) { convertedConfigs.AddRange( ValidateAndMap(config.Sonarr)); } return convertedConfigs; } private IEnumerable ValidateAndMap( IReadOnlyDictionary? configs) where TServiceConfig : ServiceConfiguration where TConfigYaml : ServiceConfigYaml { if (configs is null) { return Array.Empty(); } return configs.Select(x => _mapper.Map(x.Value) with {InstanceName = x.Key}); } }