using System; using System.Collections.Generic; using Gtk; // ReSharper disable UnusedMember.Local // ReSharper disable UnusedParameter.Local namespace Buypeeb { internal class SettingsWindow : Window { private readonly Builder builder; private readonly List generalSwitches = new(); private readonly List generalSwitchNames = new() {"ShowSecondsInListView", "Autosave", "ShowFavouritesAtTopOfList"}; private readonly Settings settings; private readonly List updateIntervalEntries = new(); private readonly List updateIntervalEntryNames = new() {"UpdateInterval", "UpdateIntervalCritical", "FavouriteUpdateInterval", "FavouriteUpdateIntervalCritical"}; public SettingsWindow(Settings settings) : this(new Builder("settings.glade"), settings) { } private SettingsWindow(Builder builder, Settings settings) : base(builder.GetObject("WindowSettings").Handle) { Title = "Buypeeb - Settings"; this.settings = settings; this.builder = builder; builder.Autoconnect(this); foreach (var name in generalSwitchNames) { var s = (Switch) builder.GetObject($"Switch{name}"); generalSwitches.Add(s); s.Active = GetSetting(PropertyName(name)); } foreach (var name in updateIntervalEntryNames) { var e = (Entry) builder.GetObject($"Entry{name}"); updateIntervalEntries.Add(e); e.Text = GetSetting(PropertyName(name)).ToString(); } } private T GetSetting(string property) { return (T) settings.GetType().GetProperty(property)?.GetValue(settings, null); } private void SetSetting(string property, T value) { settings.GetType().GetProperty(property)?.SetValue(settings, value); } private string PropertyName(string property) { // replace "PropertyName" with "propertyName"; return property[0].ToString().ToLower() + property.Substring(1); } private void ButtonSaveClicked(object sender, EventArgs args) { // first, validate all the intervals var failed = false; foreach (var name in updateIntervalEntryNames) { var e = (Entry) builder.GetObject($"Entry{name}"); if (!int.TryParse(e.Text, out var result)) { failed = true; } else { if (result is < 30 or > 6000) { failed = true; } } if (!failed) { continue; } var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Update intervals must be a whole number between 30 and 6000."); md.Run(); md.Dispose(); return; } // validation success! foreach (var name in updateIntervalEntryNames) { SetSetting(PropertyName(name), int.Parse(((Entry) builder.GetObject($"Entry{name}")).Text)); } foreach (var name in generalSwitchNames) { SetSetting(PropertyName(name), ((Switch) builder.GetObject($"Switch{name}")).Active); } Dispose(); } private void ButtonCancelClicked(object sender, EventArgs args) { Dispose(); } private void ButtonAboutClicked(object sender, EventArgs args) { var win = new AboutDialogue(); Application.AddWindow(win); win.Show(); } } }