using Compare.Helpers;
using Hl7.Fhir.Model;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.Json;

namespace Compare.Models;

internal class Config
{
    public string RootDir = FindRootDir() ?? "";
    public string ImportRelativePath { get; set; } = "testdata/R4/";
    public string ExportRelativePath { get; set; } = "testresults/R4/";
    public List<Server> Servers { get; set; } = new();
    public IEnumerable<Server> ServersEnabled => Servers.Where(server => server.Enabled);

    private static string? FindRootDir(string rootdirName = "local-env-fhirservers")
    {
        var currentDir = Directory.GetCurrentDirectory();
        bool isRootDir = false;
        while (!isRootDir && currentDir != null)
        {
            var parent = Directory.GetParent(currentDir);
            if (parent != null)
            {
                currentDir = parent?.FullName;
                isRootDir = parent?.Name == rootdirName;
            }        
        }
        if (isRootDir) return currentDir;
        throw new DirectoryNotFoundException($"RootDir: Kan map '{rootdirName}' niet vinden.");
    }

    public static Config Load()
    {
        var json = File.ReadAllText("Config.json");
        var config = JsonSerializer.Deserialize<Config>(json, Marshall.SerializerOptions) ?? throw new Exception("Config: kan Config.json niet parsen.");
        config.RootDir = FindRootDir();
        return config;
    }
}
