using System;
using System.Collections.Concurrent;
using System.Threading;

namespace MrWu.RabbitMQ {

    /// <summary>
    /// 消息池
    /// </summary>
    public class MessagePool {

        private static string m_tag;

        /// <summary>
        /// 唯一标志头
        /// </summary>
        public static string tag {
            get {
                return m_tag;
            }
            set {
                m_tag = value + DateTime.Now.Ticks;
            }
        }

        private static long id = 0;

        /// <summary>
        /// 获取id
        /// </summary>
        /// <returns></returns>
        public static string GetId() {
            return tag + Interlocked.Increment(ref id);
        }

        static MessagePool() {
            instance = new MessagePool();
        }

        private MessagePool() {
        }

        private static MessagePool instance;

        /// <summary>
        /// 消息池
        /// </summary>
        private readonly ConcurrentQueue<Message> msgs = new ConcurrentQueue<Message>();

        /// <summary>
        /// 获取一个消息
        /// </summary>
        /// <returns></returns>
        public static Message GetMessage(string msgid = null) {
            if (msgid == null)
                msgid = GetId();//Guid.NewGuid().ToString();
            Message msg = null;
            if (!instance.msgs.TryDequeue(out msg))
                msg = new Message();
            msg.isFree = false;
            msg.id = msgid;
            msg.createTime = Debug.Debug.timevalue;
            return msg;
        }

        /// <summary>
        /// 放入一个消息
        /// </summary>
        /// <param name="msg"></param>
        public static void PutMessage(ref Message msg) {
            if (msg == null)
                return;
            msg.Clear();
            msg.isFree = true;
            instance.msgs.Enqueue(msg);
            msg = null;
        }
    }
}
