using System.Text.Json;

namespace RobotNet.ScriptManager.Services;

public class DashboardConfig : BackgroundService
{
    public string[] MissionNames => [.. Config.MissionNames ?? []];
    private ConfigData Config;
    private const string DataPath = "dashboardConfig.json";
    private struct ConfigData
    {
        public List<string> MissionNames { get; set; }
    }

    public async Task UpdateMissionNames(string[] names)
    {
        Config.MissionNames = [..names];
        await File.WriteAllTextAsync(DataPath, JsonSerializer.Serialize(Config));
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        if (File.Exists(DataPath))
        {
            try
            {
                Config = JsonSerializer.Deserialize<ConfigData>(await File.ReadAllTextAsync(DataPath, CancellationToken.None));
            }
            catch (JsonException)
            {
                await File.WriteAllTextAsync(DataPath, JsonSerializer.Serialize(Config), CancellationToken.None);
            }
        }
        else await File.WriteAllTextAsync(DataPath, JsonSerializer.Serialize(Config), CancellationToken.None);
    }
}
