using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 消息管理类
    /// </summary>
    public class MessageManager : IMessageManager
    {
        /// <summary>
        /// 消息信息列表
        /// </summary>
        private List<IMessageInfo> list = new List<IMessageInfo>();

        /// <summary>
        /// 注册一个消息
        /// </summary>
        /// <param name="target">关联对象</param>
        /// <param name="action">行为</param>
        public void Register<T>(object target, Action<T> action)
        {
            if (target == null)
                throw new ArgumentNullException("target");

            if (action == null)
                throw new ArgumentNullException("target");

            lock (this.list)
            {
                MessageInfo<T> info = new MessageInfo<T>();
                info.Action = action;
                info.Target = target;
                info.Type = typeof(T);

                this.list.Add(info);
            }
        }

        /// <summary>
        /// 注销关联对象的消息
        /// </summary>
        /// <param name="target">关联对象</param>
        public void UnRegister(object target)
        {
            lock (this.list)
            {
                for (int i = 0; i < this.list.Count; ++i)
                {
                    IMessageInfo info = this.list[i];

                    if (info.Target == target)
                    {
                        this.list.RemoveAt(i);
                        --i;
                    }
                }
            }
        }

        /// <summary>
        /// 注销所有消息
        /// </summary>
        public void UnRegister()
        {
            if (this.list == null)
                return;

            lock (this.list)
            {
                this.list.Clear();
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message">消息</param>
        public void Send<T>(T message)
        {
            if (message == null)
                return;

            foreach (IMessageInfo i in this.list)
            {
                MessageInfo<T> info = i as MessageInfo<T>;

                if (info == null)
                    continue;

                info.Action(message);
            }
        }

        /// <summary>
        /// 销毁
        /// </summary>
        public void Dispose()
        {
            this.UnRegister();
            this.list = null;
        }
    }
}
