using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;


namespace VideoDistanc.Web
{
    [ServiceContract]
    public interface IChangeNotification
    {
        [OperationContract(IsOneWay = true)]
        void Notify(string message);
    }
    [ServiceContract(Namespace = "", CallbackContract = typeof(IChangeNotification))]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

    public class ChangeService
    {
        SynchronizedCollection<IChangeNotification> clients = new SynchronizedCollection<IChangeNotification>();

        [OperationContract]
        public void Suscribe(string instance)
        {
            this.clients.Add(OperationContext.Current.GetCallbackChannel<IChangeNotification>());
        }

        [OperationContract]
        public void Publish(string message)
        {
            foreach (IChangeNotification channel in this.clients)
            {
                if (channel != OperationContext.Current.GetCallbackChannel<IChangeNotification>())
                {
                    try
                    {
                        channel.Notify(message); //je treba osetrit timeoutexception
                    }
                    catch (CommunicationException)
                    {
                        // empty
                    }
                    catch (TimeoutException)
                    {
                        // empty
                    }
                }
            }
        }
    }
}
