using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Apache.NMS;
using Apache.NMS.ActiveMQ;

namespace SiaSun.LMS.Common
{
    public class ActiveMsg
    {
        #region 属性

        private string _url;
        /// <summary>服务地址
        /// 服务地址
        /// </summary>
        public string url
        {
            get
            {
                return this._url;
            }
            set
            {
                this._url = value;
            }
        }

        private IConnection _connection;
        /// <summary>连接
        /// 连接
        /// </summary>
        public IConnection connection
        {
            get
            {
                return this._connection;
            }
            set
            {
                this._connection = value;
            }
        }

        #endregion

        #region 方法

        /// <summary>构造
        /// 构造
        /// </summary>
        public ActiveMsg()
        {
            this.url = SiaSun.LMS.Common.StringUtil.GetConfig("ActiveMQUrl");
            IConnectionFactory factory = new ConnectionFactory(this.url);
            this.connection = factory.CreateConnection();
        }

        /// <summary>析构
        /// 析构
        /// </summary>
        ~ActiveMsg()
        { 
        }

        /// <summary>发送消息
        /// 发送消息
        /// </summary>
        /// <param name="sTopic">消息类型</param>
        /// <param name="sMsg">消息体</param>
        /// <param name="sResult">返回原因</param>
        /// <returns>返回结果</returns>
        public bool SendMsg( string sTopic, string sMsg, out string sResult)
        {
            bool bResult = true;

            sResult = string.Empty;

            IConnectionFactory factory = new ConnectionFactory(this._url);

            try
            {
                    //Create the Session
                    using (ISession session = this.connection.CreateSession())
                    {
                        //Create the Producer for the topic/queue
                        IMessageProducer prod = session.CreateProducer(
                            new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(sTopic));

                        //Send Messages
                        ITextMessage msg = prod.CreateTextMessage();
                        msg.Text = sMsg;

                        prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);
                    }
            }
            catch (Exception ex)
            {
                bResult = false;

                sResult = ex.Message.ToString();
            }
            finally
            {

            }

            return bResult;
        }

        #endregion
    }
}