using System.Text.Json;
using Inspectron.Epson.PrintServer.ConfigurationSources;
using Inspectron.Epson.PrintServer.PrintServices;

namespace ConfigurationPannel.Services;

public class ConfigurationManager
{
    private readonly string _configPath;
    private readonly SemaphoreSlim _configLock = new SemaphoreSlim(1, 1);
    private EpsonPrintServiceConfiguration? _currentConfig;

    public ConfigurationManager(IWebHostEnvironment env)
    {
        _configPath = Path.Combine(env.ContentRootPath, "config.json");
    }

    public async Task<EpsonPrintServiceConfiguration> LoadConfigurationAsync()
    {
        await _configLock.WaitAsync();
        try
        {
            if (File.Exists(_configPath))
            {
                var json = await File.ReadAllTextAsync(_configPath);
                _currentConfig = JsonSerializer.Deserialize<EpsonPrintServiceConfiguration>(json);
            }
            else
            {
                _currentConfig = new EpsonPrintServiceConfiguration
                {
                    GroupId = "default-group",
                    RestaurantId = "default-restaurant",
                    PrinterConfigurations = new Dictionary<string, PrinterConfiguration>()
                };
            }
            return _currentConfig!;
        }
        finally
        {
            _configLock.Release();
        }
    }

    public async Task SaveConfigurationAsync(EpsonPrintServiceConfiguration config)
    {
        await _configLock.WaitAsync();
        try
        {
            var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
            await File.WriteAllTextAsync(_configPath, json);
            _currentConfig = config;
        }
        finally
        {
            _configLock.Release();
        }
    }

    public EpsonPrintServiceConfiguration? GetCurrentConfiguration() => _currentConfig;
}
