using System.Text.Json; using PrintService.Models; namespace PrintService.Services; /// /// Loads printer-config.json (global and local), merging local over global. /// Mirrors the same logic used in PrintServiceTray. /// public class ConfigurationService { private readonly string _globalConfigPath; private readonly string _localConfigPath; private readonly ILogger _logger; public ConfigurationService(ILogger logger) { _logger = logger; _globalConfigPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "LAAPC", "printer-config.json"); _localConfigPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LAAPC", "printer-config.json"); } /// /// Load merged configuration. Returns an empty config (not null) if no files exist. /// public PrinterConfiguration Load() { var config = new PrinterConfiguration(); if (File.Exists(_globalConfigPath)) { try { var json = File.ReadAllText(_globalConfigPath); var global = JsonSerializer.Deserialize(json); if (global != null) config = global; } catch (Exception ex) { _logger.LogWarning(ex, "Failed to read global printer config from {Path}", _globalConfigPath); } } if (File.Exists(_localConfigPath)) { try { var json = File.ReadAllText(_localConfigPath); var local = JsonSerializer.Deserialize(json); if (local != null) { // Local overrides global per document type foreach (var kvp in local.DocumentTypes) config.DocumentTypes[kvp.Key] = kvp.Value; } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to read local printer config from {Path}", _localConfigPath); } } if (config.DocumentTypes.Count == 0) _logger.LogWarning("No document types found in printer-config.json. Checked: {Global} and {Local}", _globalConfigPath, _localConfigPath); return config; } /// /// Get a single document type config by name (case-insensitive). /// public DocumentTypeConfig? GetDocumentType(string documentType) { var config = Load(); return config.DocumentTypes .FirstOrDefault(kvp => kvp.Key.Equals(documentType, StringComparison.OrdinalIgnoreCase)) .Value; } }