using System;
// ReSharper disable InconsistentNaming

namespace BO.ProcessServer.Business.StatisticCounters
{
    internal class TimespanAVGCounter : TimespanCounter
    {
        public TimeSpan TotalValue { get; private set; }
        public int Items { get; private set; }

        public TimespanAVGCounter(string name) : base(name)
        {
            Items = 0;
        }

        public override void Stop()
        {
            base.Stop();
            Items++;
            TotalValue.Add(GetValueInternal());
        }

        public override object GetValue()
        {
            var msec = GetValueInternal().TotalMilliseconds;
            return TimeSpan.FromMilliseconds(msec / Items);
        }

        private TimeSpan GetValueInternal()
        {
            if (!StartTimestamp.HasValue)
                return TimeSpan.Zero;

            if (!StopTimestamp.HasValue)
                return DateTime.Now - StartTimestamp.GetValueOrDefault();

            return StopTimestamp.GetValueOrDefault() - StartTimestamp.GetValueOrDefault();
        }
    }
}
