using Edge.Core.Parser;
using Edge.Core.Parser.BinaryParser.MessageEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Edge.Core.Processor
{
    public class HistoryKeepIncoming<TMessage> : Incoming<TMessage> where TMessage : MessageBase
    {
        private List<Tuple<TMessage, DateTime>> history;
        // by seconds
        private int historyDue;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="historyDue">max time a old Message kept in history queue, by second</param>
        public HistoryKeepIncoming(int historyDue)
        {
            this.history = new List<Tuple<TMessage, DateTime>>();
            this.historyDue = historyDue;
        }

        public override TMessage Message
        {
            get { return base.Message; }
            set
            {
                this.history.Add(new Tuple<TMessage, DateTime>(value, DateTime.Now));
                var expiredItems = this.history.Where(h => DateTime.Now.Subtract(h.Item2).TotalSeconds > this.historyDue).ToList();
                foreach (var expiredItem in expiredItems)
                    this.history.Remove(expiredItem);
                base.Message = value;
            }
        }

        /// <summary>
        /// Gets or sets how long time of the messages to keep in, by second.
        /// </summary>
        public int Due
        {
            get { return this.historyDue; }
            set { this.historyDue = value; }
        }

        public List<Tuple<TMessage, DateTime>> History => this.history;
    }

}
