using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

using apiwrappercli;
using apiwrappercli.listener;
using apiwrappercli.poco.product;
using apiwrappercli.spmessage.product;
using Prism.Commands;
using Prism.Mvvm;
using SPTrader.Common;
using SPTrader.Models;

using System.Windows.Controls;

using SPTrader.Views;
using System.Linq;
using System.Windows;
using apiwrappercli.poco.account;
using SPTrader;

namespace SPTraderCore.BusinessLayer
{
    public sealed class ThrottleService
    {
        // lower throttle = refresh more freq
        private const int MAX_THROTTLE = 50;
        private SPApiProxyWrapper apiProxy;

        ConcurrentDictionary<object, int> _cd = new ConcurrentDictionary<object, int>();

        private static readonly Lazy<ThrottleService> lazy =
             new Lazy<ThrottleService>(() => new ThrottleService());

        public static ThrottleService Instance { get { return lazy.Value; } }

        private ThrottleService()
        {
            apiProxy = SPCLI.Instance.ApiProxyWrapper;
        }

        public bool AllowSPEventThrough(SPEventListener obj, int _max_throttle_throughput = MAX_THROTTLE)
        {
            if (_cd.ContainsKey(obj))
            {
                if (apiProxy.UIHelper.CanRefreshUI(obj))
                {
                    int count = _cd[obj];                    

                    if (count <= _max_throttle_throughput)
                    {
                        _cd[obj] = ++count;
                        return false;
                    }
                    else
                    {
                        _cd[obj] = 0;   // reset the count
                        return true;
                    }
                }                
            }
            else
            {
                return _cd.TryAdd(obj, 0);  // first time, allow through
            }
            return false;
        }
    }
}