Files @ 4778889395e8
Branch filter:

Location: ATITD-Tools/Desert-Paint-Codex/Models/Settings.cs

Jason Maltzen
Change the displayed permeutation count to display using locale-specific number formatting (with comma / dot separators). Fix a crash when starting a new round of recipe generation after recipe generation completed during a previous run.
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace DesertPaintCodex.Models
{
    internal class Settings
    {
        private readonly Dictionary<string, string> _settings = new();

        public bool TryGet(string key, out int value)
        {
            value = 0;
            return _settings.TryGetValue(key.ToLower(), out string? valStr)
                && int.TryParse(valStr, out value);
        }
        public bool TryGet(string key, out bool value)
        {
            value = false;
            return _settings.TryGetValue(key.ToLower(), out string? valStr)
                && bool.TryParse(valStr, out value);

        }
        public void Set(string key, int value)
        {
            _settings[key.ToLower()] = value.ToString();
        }
        public void Set(string key, bool value)
        {
            _settings[key.ToLower()] = value.ToString();
        }

        public void Reset()
        {
            _settings.Clear();
        }

        public void Save(string settingsPath)
        {
            using StreamWriter writer = new(settingsPath);
            foreach (KeyValuePair<string, string> pair in _settings)
            {
                writer.WriteLine("{0}={1}", pair.Key, pair.Value);
            }
        }

        private static readonly Regex OptionEntry = new(@"(?<opt>[^#=][^=]*)=(?<optval>.*)$");
        
        public bool Load(string settingsPath)
        {
            if (!File.Exists(settingsPath)) return false;
            using StreamReader reader = new(settingsPath);
            string? line;
            while ((line = reader.ReadLine()) != null)
            {
                Match match = OptionEntry.Match(line);
                
                if (!match.Success) continue;
                
                string optName = match.Groups["opt"].Value.ToLower();
                string optVal  = match.Groups["optval"].Value.Trim();
                if (optName.Equals("debug"))
                {
                    // convert
                    optName = "enabledebugmenu";
                }
                _settings[optName.ToLower()] = optVal;
            }

            return true;
        }
    }
}