﻿using System;
using System.Text;
using System.Threading;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace Receive
{
    class Worker
    {
        private const string ChannelName = "task_queue2";

        public static void Main(string[] args)
        {
            // Here we connect to a broker on the local machine - hence the localhost. 
            // If we wanted to connect to a broker on a different machine we'd simply 
            // specify its name or IP address here.
            var factory = new ConnectionFactory() { HostName = "localhost" };

            // The connection abstracts the socket connection, and takes care of protocol 
            // version negotiation and authentication and so on for us.
            using (var connection = factory.CreateConnection())
            {
                // we create a channel, which is where most of the API for getting things 
                // done resides.
                using (var channel = connection.CreateModel())
                {
                    // To send, we must declare a queue for us to send to; then we can 
                    // publish a message to the queue.
                    // Declaring a queue is idempotent - it will only be created if it 
                    // doesn't exist already. The message content is a byte array, so 
                    // you can encode whatever you like there.
                    channel.QueueDeclare(ChannelName, true, false, false, null);

                    channel.BasicQos(0, 1, false);
                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(ChannelName, false, consumer);

                    Console.WriteLine(" [*] Waiting for messages. " +
                                      "To exit press CTRL+C");
                    while (true)
                    {
                        var ea =
                            (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received {0}", message);

                        int dots = message.Split('.').Length - 1;
                        Thread.Sleep(dots * 1000);

                        Console.WriteLine(" [x] Done");

                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                }
            }
        }
    }
}
