Winify – Rev 12

Subversion Repositories:
Rev:
using System;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.Linq;
using Servers;

namespace Winify.Gotify
{
    public class GotifyConnectionManager : IDisposable
    {
        #region Public Events & Delegates

        public event EventHandler<GotifyNotificationEventArgs> GotifyNotification;

        #endregion

        #region Private Delegates, Events, Enums, Properties, Indexers and Fields

        private readonly ConcurrentDictionary<string, GotifyConnection> _gotifyConnections;

        private readonly global::Servers.Servers _servers;

        #endregion

        #region Constructors, Destructors and Finalizers

        private GotifyConnectionManager()
        {
            _gotifyConnections = new ConcurrentDictionary<string, GotifyConnection>();
        }

        public GotifyConnectionManager(global::Servers.Servers servers) : this()
        {
            _servers = servers;

            _servers.Server.CollectionChanged += Server_CollectionChanged;
        }

        public void Dispose()
        {
            _servers.Server.CollectionChanged -= Server_CollectionChanged;
        }

        #endregion

        #region Event Handlers

        private void Server_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (var server in e.NewItems.OfType<Server>())
                {
                    var connection = new GotifyConnection();
                    connection.GotifyNotification += Connection_GotifyNotification;

                    connection.Start(server.Username, server.Password, server.Url);
                    _gotifyConnections.TryAdd(server.Name, connection);
                }
            }

            if (e.OldItems != null)
            {
                foreach (var server in e.OldItems.OfType<Server>())
                {
                    if (!_gotifyConnections.TryRemove(server.Name, out var gotifyConnection))
                    {
                        continue;
                    }

                    gotifyConnection.GotifyNotification -= Connection_GotifyNotification;

                    gotifyConnection.Stop();
                    gotifyConnection.Dispose();
                }
            }
        }

        private void Connection_GotifyNotification(object sender, GotifyNotificationEventArgs e)
        {
            GotifyNotification?.Invoke(sender, e);
        }

        #endregion
    }
}

Generated by GNU Enscript 1.6.5.90.