using System.Text.Json;

namespace Universal;

public class JsonHelper
{
    public static bool ReadFile<T>(string filePath, out T? output)
    {
        output = default;
        if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            return false;

        using StreamReader sr = new(filePath);
        try
        {
            string jsonContent = sr.ReadToEnd();
            output = JsonSerializer.Deserialize<T>(jsonContent);
        }
        catch
        {
            return false;
        }

        return true;
    }

    public static bool WriteFile<T>(string filePath, T input)
    {
        if (input is null || string.IsNullOrEmpty(filePath))
            return false;

        try
        {
            FileInfo file = new(filePath);

            if (file.Directory is not DirectoryInfo directory)
                return false;

            if (!Directory.Exists(directory.FullName))
                Directory.CreateDirectory(directory.FullName);

            string jsonContent = JsonSerializer.Serialize(input);
            using StreamWriter sw = new(filePath, false);
            sw.WriteLine(jsonContent);
        }
        catch
        {
            return false;
        }

        return true;
    }

}
