using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using Apache.NMS.ActiveMQ.Commands;
using Apache.NMS;
using PushPlatform.Common.Enumerate;

namespace PushPlatform.Common.Mq
{
    public class ActiveMQHelper
    {
        /// <summary>
        /// 获取服务器地址
        /// </summary>
        private static string ActiveMQConfig = ConfigurationManager.AppSettings["ActiveMQ"];


        /// <summary>
        /// 创建一个生产者消息
        /// </summary>
        /// <param name="QueueName">消息队列名称</param>
        /// <param name="mqmode">消息类型</param>
        /// <param name="DataCenterMessage">传递消息</param>
        /// <param name="UserName">账号，如果不填默认使用Admin</param>
        /// <param name="Password">密码，如果不填默认使用Admin</param>
        public static void CreateMQProducer(string QueueName, MQMode mqmode, DataCenterMessage DataCenterMessage, DateTime SendDatetime, string UserName = "Admin", string Password = "Admin")
        {
            using (ActiveMQProducer producer = new ActiveMQProducer())
            {

                producer.BrokerUri = ActiveMQConfig;
                producer.UserName = UserName;
                producer.Password = Password;
                producer.QueueName = QueueName;
                producer.MQMode = mqmode;


                //发送到队列, Put对象类必须使用[Serializable]注解属性
                producer.Put(DataCenterMessage, SendDatetime);
            }

        }




        /// <summary>
        /// 创建一个消费者
        /// </summary>
        /// <param name="QueueName">消息队列名称</param>
        /// <param name="mqmode">消息类型</param>
        /// <param name="MessageReceived"></param>
        /// <param name="DataCenterMessageReceived">消息返回结果</param>
        /// <param name="UserName">账号，如果不填默认使用Admin</param>
        /// <param name="Password">密码，如果不填默认使用Admin</param>
        public static void CreateMQConsumer(string QueueName, MQMode mqmode, Action<DataCenterMessage> DataCenterMessageReceived, string UserName = "Admin", string Password = "Admin")
        {
            ActiveMQConsumer consumer = new ActiveMQConsumer();


            consumer.BrokerUri = ActiveMQConfig;
            consumer.UserName = UserName;
            consumer.Password = Password;
            consumer.QueueName = QueueName;
            consumer.MQMode = mqmode;
            consumer.OnMessageReceived = (msg) =>
            {
                var bytesMessage = msg as ActiveMQBytesMessage;
                if (bytesMessage != null)
                {
                    var buffer = new byte[bytesMessage.BodyLength];
                    bytesMessage.WriteBytes(buffer);
                    var result = buffer.ToObject<DataCenterMessage>();
                }
            };
            consumer.OnDataCenterMessageReceived = DataCenterMessageReceived;
            
            consumer.StartListen();
        }
    }

}

