Files @ a78dba5bed0e
Branch filter:

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

Jason Maltzen
Add stub view model code for recipe library (future feature work)
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;
            bool found = _settings.TryGetValue(key.ToLower(), out string? valStr);
            found = found && bool.TryParse(valStr, out value);
            return found;

        }
        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;
        }
    }
}