using System;

namespace BO.ProcessServer.Business.StatisticCounters
{
    internal class TimespanCounter : BaseCounter
    {

        public bool IsRunning { get; private set; }
        public DateTime? StartTimestamp { get; private set; }
        public DateTime? StopTimestamp { get; private set; }

        public TimespanCounter(string name) : base(name)
        {
        }

        public TimeSpan GetTypedValue()
        {
            return (TimeSpan) GetValue();
        }

        public override object GetValue()
        {
            if (!StartTimestamp.HasValue)
                return TimeSpan.Zero;

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

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

        public virtual void Start()
        {
            if (IsRunning)
                throw new InvalidOperationException($"Cannot start counter '{Name}' is already running.");
            IsRunning = true;
            StartTimestamp = DateTime.Now;
        }

        public virtual void Stop()
        {
            if (!IsRunning)
                return;
            IsRunning = false;
            StopTimestamp = DateTime.Now;
        }

        public override void Reset()
        {
            IsRunning = false;
            StartTimestamp = null;
            StopTimestamp = null;
        }
    }
}
