using EasyNetQ;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MQTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //关闭线程安全检查，关闭后可以像下面代码一样直接修改空间Text属性值，否则会报错，需要使用Invoke方法
            CheckForIllegalCrossThreadCalls = false;
        }
        private IBus bus1;
        private IBus bus2;
        private IBus bus3;
        private string connectionStr = "host=127.0.0.1;virtualHost=myvhost;username=guest;password=guest;requestedHeartbeat=10";
        private void button1_Click(object sender, EventArgs e)
        {
            bus1 = RabbitHutch.CreateBus(connectionStr);
            var message = new MyMessage { Text = richTextBox1.Text };
            //发布消息
            bus1.Publish(message);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bus2 = RabbitHutch.CreateBus(connectionStr);
            //订阅消息
            //点击按钮订阅，订阅后只要发布新的消息，收到消息后就会执行修改richTextBox2.Text的值
            //用同一个subscribeid订阅了同一种消息类型两次或者多次，RabbitMQ会轮着给两个订阅发消息（两个订阅不会同时收到消息）
            bus2.Subscribe<MyMessage>("subscribeid_1", (msg) => {
                string value = msg.Text;
                richTextBox2.Text += value+"\r\n";
            });
        }

        private void button3_Click(object sender, EventArgs e)
        {
            bus3 = RabbitHutch.CreateBus(connectionStr);
            bus3.Subscribe<MyMessage>("subscribeid_2", (msg) =>
            {
                string value = msg.Text;
                richTextBox3.Text += value + "\r\n";
            });
        }
        private void Form1_FormClosed_1(object sender, FormClosedEventArgs e)
        {
            if (bus1 != null)
            {
                bus1.Dispose();
            }
            if (bus2 != null)
            {
                bus2.Dispose();
            }
            if (bus3 != null)
            {
                bus3.Dispose();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.ShowDialog();
        }
    }
}
