using System; using System.Collections.Generic; using Gtk; namespace Buypeeb { class SettingsWindow : Window { private List generalSwitches = new List(); private List updateIntervalEntries = new List(); private Settings settings; private Builder builder; private List generalSwitchNames = new List { "ShowSecondsInListView", "Autosave", "ShowFavouritesAtTopOfList" }; private List updateIntervalEntryNames = new List { "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) { this.Title = "Buypeeb - Settings"; this.settings = settings; this.builder = builder; builder.Autoconnect(this); foreach (var name in this.generalSwitchNames) { var s = (Switch)builder.GetObject($"Switch{name}"); this.generalSwitches.Add(s); s.Active = GetSetting(this.PropertyName(name)); } foreach (var name in this.updateIntervalEntryNames) { var e = (Entry)builder.GetObject($"Entry{name}"); this.updateIntervalEntries.Add(e); e.Text = GetSetting(this.PropertyName(name)).ToString(); } } private T GetSetting(string property) { return (T)this.settings.GetType().GetProperty(property).GetValue(this.settings, null); } private void SetSetting(string property, T value) { this.settings.GetType().GetProperty(property).SetValue(this.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 bool failed = false; foreach (var name in this.updateIntervalEntryNames) { var e = (Entry)builder.GetObject($"Entry{name}"); if (!int.TryParse(e.Text, out int result)) { failed = true; } else { if (result < 30 || result > 6000) { failed = true; } } if (failed) { 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 this.updateIntervalEntryNames) { this.SetSetting(PropertyName(name), int.Parse((builder.GetObject($"Entry{name}") as Entry).Text)); } foreach (var name in this.generalSwitchNames) { this.SetSetting(PropertyName(name), (builder.GetObject($"Switch{name}") as Switch).Active); } this.Dispose(); } private void ButtonCancelClicked(object sender, EventArgs args) { this.Dispose(); } } }