using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Now.Business; using Now.Entities; using Now.Web.Hubs; namespace Now.Web.Tickers { public class ConsolidationTicker { private readonly static Lazy _instance = new Lazy(() => new ConsolidationTicker(GlobalHost.ConnectionManager.GetHubContext().Clients)); private readonly object _update = new object(); private readonly TimeSpan _updateInterval = TimeSpan.FromMilliseconds(3000); private readonly Timer _timer; private volatile TotalDeliveryCosts _prevTotalDeliveryCosts = null; private IHubConnectionContext Clients { get; set; } public ConsolidationTicker(IHubConnectionContext clients) { Clients = clients; _timer = new Timer(UpdateDeliveryCostsTimerCallback, null, _updateInterval, _updateInterval); } public static ConsolidationTicker Instance { get { return _instance.Value; } } private void UpdateDeliveryCostsTimerCallback(object state) { UpdateDeliveryCosts(false); } private void UpdateDeliveryCosts(bool force) { lock (_update) { TotalDeliveryCosts totalDeliveryCosts = ConsolidationWorkflow.Instance.GetTotalDeliveryCosts(); if (force || _prevTotalDeliveryCosts != totalDeliveryCosts) { BroadcastDeliveryCosts(ConsolidationWorkflow.Instance.GetDispatchedOrdersStats()); BroadcastCountriesSummary(ConsolidationWorkflow.Instance.GetDeliveryCostCountriesStatistics()); BroadcastTotalDeliveryCosts(totalDeliveryCosts); _prevTotalDeliveryCosts = totalDeliveryCosts; } } } internal void OnConsolidationHubConnected() { UpdateDeliveryCosts(true); } private void BroadcastCountriesSummary(IEnumerable summary) { if (summary != null) Clients.All.updateDeliveryCostCountriesSummary(summary); } private void BroadcastDeliveryCosts(IEnumerable summary) { if (summary != null) Clients.All.updateDeliveryCost(summary); } private void BroadcastTotalDeliveryCosts(TotalDeliveryCosts summary) { if(summary != null) Clients.All.updateTotalDeliveryCost(summary); } } }