using Serilog; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace TINK.ViewModel.Settings { /// ViewModel for an active service plus a list of services which are not active. /// /// Example for services are lock services, geolocation services, ..., /// public class ServicesViewModel : INotifyPropertyChanged { /// Active service. private string active; /// Holds the dictionary which maps services to service display texts. private IDictionary ServiceToText { get; } /// Holds the dictionary which maps service display texts to services. private IDictionary TextToService { get; } /// Constructs view model ensuring consistency. /// List of available services. /// Dictionary holding display text for services as values. /// Active service. public ServicesViewModel( IEnumerable services, IDictionary serviceToText, string active) { if (!services.Contains(active)) throw new ArgumentException($"Can not instantiate {typeof(ServicesViewModel).Name}- object. Active lock service {active} must be contained in [{String.Join(",", services)}]."); ServiceToText = services.Distinct().ToDictionary( x => x, x => serviceToText.ContainsKey(x) ? serviceToText[x] : x); TextToService = ServiceToText.ToDictionary(x => x.Value, x => x.Key); Active = active; } /// Fired whenever active service changes. public event PropertyChangedEventHandler PropertyChanged; /// Holds active service. public string Active { get => active; set { if (active == value) return; active = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Active))); } } /// List of display texts of services. public IList ServicesTextList => ServiceToText.Select(x => x.Value).OrderBy(x => x).ToList(); /// Active locks service. public string ActiveText { get => ServiceToText[Active]; set { if (!TextToService.ContainsKey(value)) { Log.ForContext().Error($"Can not set service {value} to services view model. List of services {{{string.Join(";", TextToService)}}} does not hold machting element."); throw new ArgumentException($"Can not set service {value} to services view model. List of services {{{string.Join(";", TextToService)}}} does not hold machting element."); } Active = TextToService[value]; } } } }