using TShockAPI;
using Newtonsoft.Json;

namespace ProgressionGates
{
    internal static class Config
    {
        private static readonly string ConfigFile = Path.Combine(TShock.SavePath, "ProgressionGates.config");
        internal static void Load()
        {
            if (File.Exists(ConfigFile))
            {
                try
                {
                    string json = File.ReadAllText(ConfigFile);
                    var loadedGates = JsonConvert.DeserializeObject<Dictionary<Engagements, EngagementGate>>(json);
                    if (loadedGates != null)
                    {
                        ProgressionGates.Gates = loadedGates;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error loading config: {ex.Message}");
                }
            }

            /* Default to all engagements being unavailable if no file exists */
            var defaultGates = Enum.GetValues<Engagements>().Where(e => e != Engagements.UnusedOrError)
                .ToDictionary(e => e, e => new EngagementGate(e, DateTime.MaxValue));
            ProgressionGates.Gates = new Dictionary<Engagements, EngagementGate>(defaultGates);
            SaveConfig();
        }

        internal static void SaveConfig()
        {
            try
            {
                string config = JsonConvert.SerializeObject(ProgressionGates.Gates, Formatting.Indented);
                File.WriteAllText(ConfigFile, config);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error saving config: {ex.Message}");
            }
        }
    }
}